angular 2如何将服务响应数据传递给UI
问题描述:
我对angular 2相当陌生,并且坚持一个基本问题。angular 2如何将服务响应数据传递给UI
显示的UI我的组件是这样的: chat.ts
@IonicPage()
@Component({
selector: 'page-chat',
templateUrl: 'chat.html',
providers: [ChatService]
})
export class ChatPage {
items: SimpleMessage[] = [];
createChatBubble(chatMessage: string){
//alert(this.chatMessage);
this.items.push(new SimpleMessage(chatMessage));
}
}
聊天service.ts
@Injectable()
export class ChatService {
openSocket(){
this.ws = new WebSocket('ws://' + this.host + '/chat/ws');
this.ws.addEventListener('message', event => {
this.zone.run(() => {
var msg = JSON.parse(event.data);
this.broadcast(msg);
});
});
broadcast(msg){
let message = this.parseModel(msg);
let chatReply = new SimpleMessage(message, 'bot');
}
}
所以,从服务器中broadbast功能需求收到消息以某种方式传递给chat.ts项目对象。请告知
答
您可以使用服务和您从组件订阅的observable。
编辑: 我写了另一个例子。 我不会写一个套接字,但我写了一个子组件,它触发点击按钮上的某个事件。整个应用程序可以下载here。
服务
import {Injectable} from '@angular/core';
import {Subject} from 'rxjs/Subject';
@Injectable()
export class CommunicateService {
// source of change
private newStringSource = new Subject<string>();
// observable
public stringCreated = this.newStringSource.asObservable();
public sendNewString(newString: string): void {
// broadcasts the new data to every listener
this.newStringSource.next(newString);
}
}
应用组件
import {Component, OnInit} from '@angular/core';
import {CommunicateService} from './communicate.service';
@Component({
selector: 'app-root',
template: `<h1>
{{title}}
<app-child></app-child>
</h1>
`
})
export class AppComponent implements OnInit {
title = 'app works!';
constructor(private communicateService: CommunicateService) {
}
ngOnInit(): void {
this.communicateService.stringCreated.subscribe(event => {
console.log(event);
});
}
}
孩子与一个按钮触发
import {Component, OnInit} from '@angular/core';
import {CommunicateService} from '../communicate.service';
@Component({
selector: 'app-child',
template: `<p>
child works!
<button (click)="onClick()"> Click me </button>
</p>
`
})
export class ChildComponent {
constructor(private communicateService: CommunicateService) {
}
onClick() {
for (var i = 0; i < 10; i++)
this.communicateService.sendNewString(`i is ${i}`); // string interpolation
}
}
所以,你想要做的是什么,而不是注入的服务到子补偿这里,将其注入套接字服务并在您接收新数据时调用sendNewString。
希望它有帮助。
都需要componentChangeSource和newDateCreationSource还是只需要两个不同的变体? – Vik
只是不同的变化,显示不一定需要传递一些数据。 – LLL
其中componentChanged $在服务中声明?这到底意味着什么? – Vik