Why observable.subscribe works only from constructor

断了今生、忘了曾经 提交于 2019-12-05 13:43:37
theriddle2

It has to do with Angular change detection, for more info about this, read: Angular Change detection.

You should use Angular ngZone service to solve this, it will update the view.

import { Component, NgZone } from "@angular/core";

constructor(
    private ngZone: NgZone
    ...
){ }

...
ngOnInit() {
    this.myService.myObservable.subscribe((data) => {
        this.ngZone.run(()  => {
            this.myVariable = data;
        });
    });
}

You do not clarify what kind of observable you have (e.g. 'cold', 'hot', Subject, BehaviorSubject, an HttpClient observable, etc.). If it is an observable that you have created yourself, it may well be that its value changed before you subscribe to it in the ngOnInit method and therefore depending on the type of observable the value is lost. Since the service that created the observable is injected in the constructor, the constructor gets earlier access to whatever value may be emitted by the service. If you are constructing the observable yourself, consider using a BehaviorSubject:

What is the difference between Subject and BehaviorSubject?

use private myService

contructor(private myService: MyService) {
  this.myService.myObservable.subscribe((data) => {
    this.myVariable = data;
  });
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!