如何根据第一个组件收到的 websocket 事件更新第二个组件中的内容



我有一个用组件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。

您可以按如下方式使用共享服务和可观察。

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
});

如果组件处于父/子关系中,您也可以执行此操作:

组件 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
    }
  }
}

相关内容

最新更新