The best way to share WebSocket data between multiple components in Angular 2?

前端 未结 2 877
名媛妹妹
名媛妹妹 2020-12-10 05:52

I start to build an application. There are a lot of components. Each of them need a part of data from 1 webSocket. The example of a receiveing object by webSocket:

<

相关标签:
2条回答
  • 2020-12-10 06:50

    Sure you can share your service by set its provider when bootstrapping the application:

    bootstrap(AppComponent, [ WebSocketService ]);
    

    This way you will share the same instance of your service in the whole application. I mean when you inject the WebSocketService service, the corresponding instance will be the same whatever the component / service.

    To be able to share the received data, I would leverage an hot observable. By default observables are cold so you need to use the share operator.

    initializeWebSocket(url) {
      this.wsObservable = Observable.create((observer) => {
        this.ws = new WebSocket(url);
    
        this.ws.onopen = (e) => {
          (...)
        };
    
        this.ws.onclose = (e) => {
          if (e.wasClean) {
            observer.complete();
          } else {
            observer.error(e);
          }
        };
    
        this.ws.onerror = (e) => {
          observer.error(e);
        }
    
        this.ws.onmessage = (e) => {
          observer.next(JSON.parse(e.data));
        }
    
        return () => {
          this.ws.close();
        };
      }).share();
    }
    

    Components that would like to receive data from the web socket could use this observable this way:

    @Component({
      (...)
    })
    export class SomeComponent {
      constructor(private service:WebSocketService) {
        this.service.wsObservable.subscribe((data) => {
          // use data
        });
      }
    }
    

    See this article for more details in the "event-based approach" section:

    • https://jaxenter.com/reactive-programming-http-and-angular-2-124560.html
    0 讨论(0)
  • 2020-12-10 06:53

    Something like the following (depending on your concrete requirements):

    @Injectable()
    class WsService {
      comp1Data = new BehaviorSubject();
      comp2Data = new BehaviorSubject();
    
      constructor() {
        getData().subscribe( val => {
          ...
          this.compXData.next(someValue);
        });
      }
      ...
    }
    
    @Component({...}) 
    export class Component1 {
      constructor(wsService:WsService) {
        wsService.comp1Data.subscribe(value => this.data = value);
      }
    }
    
    @NgModule({
       directives: [AppComponent, Component1],
       bootstrap: [AppComponent],
       providers: [WsService, ...]
    });
    
    0 讨论(0)
提交回复
热议问题