简体   繁体   中英

Angular2 Observable not triggering rerendering

TLDR: Observable object doesn't trigger component rerendering until an action is made by the user (click on a button for example).

I'm updating an observable backed by a BehaviorSubject contained inside a service that is injected inside my component.

In my component, I'm using a simple *ngIf="myObservable$ | async" to display a div.

I managed to replicate 2 situations, one working and one that doesn't but I can't understand what's the difference:

//CASE 1
this._mySubject$.next(true); //THIS DOES TRIGGER RERENDERING
//CASE 2
this.http.get(url)
.map( res => res.json() )
.subscribe( body => {
    this._mySubject$.next(true); //THIS DOESN'T TRIGGER RERENDERING UNTIL AN ACTION IS MADE
});

If you need to do side effects try to do it in the do operator

this.http.get(url)
.map( res => res.json() )
.do( () => this._mySubject$.next(true))
.subscribe();

It might be a better idea to subscribe to the behavior subject in the ngOnInit method and set a property to use in the ngIf. Since the actual object is not a new object just a new emission from the behavior subject it is probably not triggering Angular's change detection. It seems to play best with immutable objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM