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

时间:2018-03-15 05:46:03

标签: angular typescript websocket 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
        }
    });

我想知道每当我在旅途中收到websocket事件时如何更新组件B.

2 个答案:

答案 0 :(得分:7)

您可以按如下方式使用共享服务和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);
  }
}

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

答案 1 :(得分:1)

如果组件处于父/子关系中,您也可以这样做:

组件A(父母):

this.socketService.connect('/socket_url');
    this.statusSubscription = this.socketService.messages
      .subscribe(result => {
        if (result !== 'pong') {
            this.componentBdata = result;
        }
    });

在componentA.html

<componenB [data]="componentBdata "> </componentB>

在componentB(child)中:

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

}