【问题标题】:How to update contents in a second component based on websocket event received at first component?如何根据第一个组件收到的 websocket 事件更新第二个组件中的内容?
【发布时间】:2018-03-15 05:46:03
【问题描述】:
我有一个用组件 A 编写的 websocket 逻辑,如下所示。
this.socketService.connect('/socket_url');
this.statusSubscription = this.socketService.messages
.subscribe(result => {
if (result !== 'pong') {
// update Component B with the response obtained
}
});
我想知道如何在旅途中收到 websocket 事件时更新组件 B。
【问题讨论】:
标签:
angular
typescript
websocket
angular5
【解决方案1】:
您可以按如下方式使用共享的 Service 和 Observable。
shared-data.service.ts
import {Injectable} from '@angular/core';
import {Subject} from 'rxjs/Subject';
import {Observable} from 'rxjs/Observable';
@Injectable()
export class SharedDataService {
public userStatusToggle: Observable<any>;
private userStatusSubject = new Subject<any>();
constructor() {
this.userStatusToggle = this.userStatusSubject.asObservable();
}
notifyUserStatusChange(data) {
this.userStatusSubject.next(data);
}
}
组件 A
.
.
.
constructor(private sharedDataService: SharedDataService) {
}
this.socketService.connect('/socket_url');
this.statusSubscription = this.socketService.messages
.subscribe(result => {
if (result !== 'pong') {
this.sharedDataService.notifyUserStatusChange(result);
}
});
组件 B
.
.
.
constructor(private sharedDataService: SharedDataService) {
}
this.sharedDataService.userStatusToggle.subscribe(userStatus => {
// Do action with the 'userStatus' obtained
});
【解决方案2】:
如果组件处于父/子关系中,您也可以这样做:
组件 A(父):
this.socketService.connect('/socket_url');
this.statusSubscription = this.socketService.messages
.subscribe(result => {
if (result !== 'pong') {
this.componentBdata = result;
}
});
在组件A.html中
<componenB [data]="componentBdata "> </componentB>
在组件B(子)中:
export class ComponentB implements OnChanges, OnInit {
@Input() data: string;
private _data: string;
constructor() {}
ngOnChanges(changes: SimpleChanges) {
const data: SimpleChange = changes.data;
if(data.previousValue ! = data.currentValue){
this._data = data.currentValue;
// do your change here
}
}
}