Angular: Binding to a observable property of service -> value doesn't update

断了今生、忘了曾经 提交于 2019-12-23 16:06:57

问题


I'm trying to communicate between two browser tabs/windows using BroadcastChannel API. The communication seems to work between two instances of angular service, but changes to the values of the observable are not shown. I'm trying to achieve this using mainly the async pipe.

I have a demo of my problem at StackBlitz

I have two component that are showed using the router. (controland display)

I have a service (MessagingService) where I have a BehaviorSubject and BroadcastChannel API -communications. That service is injected into both components.

  export class MessagingService {
  private _value = 1;
  valueSubject: BehaviorSubject<number> = new BehaviorSubject<number>(this._value);
  value$: Observable<number> = this.valueSubject.asObservable();

  private bc: BroadcastChannel = new BroadcastChannel('controlChannel');

  constructor() {
    this.bc.onmessage = this.handleEvent;
  }

When I open two tabs (one in /control and one in /display) I can increment the value in /control and to receive the new values in /display at console but the values wont be updated.

Binding: <p>service value: {{ messenger.value$ | async }}</p>

Injection: constructor(private messenger: MessagingService) { }

So the question is, what I'm doing wrong? I made additional subscription in displayand the fires the next call but the async binding doesn't get updated. I'm also seeing the correct MessageEvent in that same tab with correct value in data.

EDIT: Additional testing shows that the value is updated when the button for changing local value is pressed. So it seems to be an issue with change detection.


回答1:


If you are mutating data outside of the angular context (i.e., externally), then angular will not know of the changes. You need to use ChangeDetectorRef or NgZone in your component for making angular aware of external changes and thereby triggering change detection.

In your case, Probably your service somehow breaks out of Angular's zone. That's why Angular is unable to detect Changes

This Should Work

   import { Component, OnInit, OnDestroy, NgZone } from '@angular/core';
@Component({
  selector: 'app-display',
  template:
    //.....rest of the code
    constructor(private messenger: MessagingService,private zone: NgZone,) {}

   ngOnInit() {
    this.data = new Data();
    this.sub = this.messenger.value$.subscribe(
      res => {
        this.zone.run(() => this.data.value = res)
      }
    );
  }
  1. ZONES IN ANGULAR
  2. UNDERSTANDING ZONES
  3. ANGULAR CHANGE DETECTION EXPLAINED

Forked StackBlitz



来源:https://stackoverflow.com/questions/51270534/angular-binding-to-a-observable-property-of-service-value-doesnt-update

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!