Angular2 Observable not firing the first time

2019-05-30 03:00发布

Good day!

A small problem with Angular2 after updating from RC5 to latest version. I am using a service to communicate between components. The service exposes an Observable to allow subscriptions, and it is declared in the app.module. In the console it seems to contain the data from the first click along with the available subscribers.

Now, when I click the button on the component that calls the fetch method, nothing happens. However, if I click it again the results are displayed successfully. I have searched online but could not find an answer.

With angular2 rc5 the same code was working as expected until the update.

Parts from the service:

items: Observable<Array<Object>>;
private _data: BehaviorSubject<Array<Object>>;

constructor(private http: Http) {
    this._data = new BehaviorSubject(null);
    this.items = this._data.asObservable();
}

fetch(text: String) {
    this.text = text;
    let headers = new Headers();
    headers.append("Content-Type", "application/json");
    let options = new RequestOptions({ headers: headers });
    this.http.post(this._url, "...{}...", options)
        .map((res: Response) => res.json())
        .subscribe(data => {
            this._data.next(Object.assign([], data).items);
        }, error => this.handleError(error));
}

The component code where it should be updated. (Btw the component is inside a <router-outlet>)

component:
    private data: Array<Object>;

    ngOnInit() {
        this.fetchService.items.subscribe(result => {
            this.data = result;
        });
    }

Anyone who can shed some light on what is wrong?

1条回答
Anthone
2楼-- · 2019-05-30 03:18

it looks like a bug in angular2. I had similar problem and I found a workaround. Here it is.

component:
private data: Array<Object>;

constructor(private changeDetectorRef: ChangeDetectorRef) { }

ngOnInit() {
    this.fetchService.items.subscribe(result => {
        this.data = result;
        this.changeDetectorRef.detectChanges();
    });
}

You have to inject the changeDetector and fire manually change detection after data change.

Hope it helps;)

查看更多
登录 后发表回答