Angular2: view is not updated from inside a subscription

前端 未结 1 909
轮回少年
轮回少年 2021-01-17 01:47

I have a simple angular2 (rc1) component which subscribes to a service. When the service updates the subscription, I can log the result in the component\'s subscription bu

1条回答
  •  星月不相逢
    2021-01-17 02:02

    It looks like _uploaderService runs outside Angulars zone. Angular won't detect changes when values are changed from outside its zone.

    To make the code to run inside the zone use

      constructor(private _uploaderService: UploaderService, private zone:NgZone) {
        // view correctly shows this value:
        this.successMessage.serverMessage = 'before ';
        this.subscription = _uploaderService.fileSuccess$.subscribe(result => {
            // this fires and logs the result correctly:
            console.log('the mini uploader: type of result', result);
            // view is never updated here
    
            this.zone.run(() => this.successMessage = result);
          })
      }
    

    There are also other ways to notify Angular about changes Manual Change Detection in AngularJS or Angular 2?

    If there is additional code run like when router.navigate() is called outside the zone, only zone.run(...) will properly solve the issue - except when there is a way to make your service run inside Angulars zone in the first place.

    0 讨论(0)
提交回复
热议问题