Ash*_*hok 3 websocket typescript angular angular5
我有一个在组件A中编写的websocket逻辑,如下所示.
this.socketService.connect('/socket_url');
this.statusSubscription = this.socketService.messages
.subscribe(result => {
if (result !== 'pong') {
// update Component B with the response obtained
}
});
Run Code Online (Sandbox Code Playgroud)
我想知道每当我在旅途中收到websocket活动时如何更新组件B.
您可以使用共享服务和Observable,如下所示.
共享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);
}
}
Run Code Online (Sandbox Code Playgroud)
组件A.
.
.
.
constructor(private sharedDataService: SharedDataService) {
}
this.socketService.connect('/socket_url');
this.statusSubscription = this.socketService.messages
.subscribe(result => {
if (result !== 'pong') {
this.sharedDataService.notifyUserStatusChange(result);
}
});
Run Code Online (Sandbox Code Playgroud)
组件B.
.
.
.
constructor(private sharedDataService: SharedDataService) {
}
this.sharedDataService.userStatusToggle.subscribe(userStatus => {
// Do action with the 'userStatus' obtained
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
67 次 |
| 最近记录: |