Search code examples
angularrxjsngrxngrx-store

angular 4 variable not updating the first time


Here is the problem I am facing.

I have a variable inside a component which assigned to a directive. I am using ngrx to dispatch and susbcribe to events. So the problem is that the variable does not update the first time. After that there is no problem.

I have a google map and icons on it and on click of any icon it makes a call to the server with the id and map bounds and then with the returned data an action is dispatched.

private getFromServer(id, bound_corners){
    let params = { bounds: bound_corners }
    return this.restangular.all('get-data/'+id)
            .customGET("", params)
            .map((d:any)=>{
                return d.plain();
            });
}

public onClick(icon){
    let bound_corners = this.getMapBounds();

    this.getFromServer(icon.id, bound_corners).subscribe((d)=>{

        this.store.dispatch(new action.detail(d, id));

    });
}

In the component class

let temp = store.select(fromRoot.getIconDetail);

temp.subscribe((d)=>{
    this.data = d;
})

In the component this.data does not get updated the first time. If I console log(this.data) then it works but it does not get updated in the html.

If I take the dispatch action out of the getFromServer subscription like this:

public onClick(icon){
    let bound_corners = this.getMapBounds();

    let temp_data = {name:"test","id":0};

    this.store.dispatch(new action.detail(temp_data, id));
}

then it works.

Currently I have one solution which is using ChangeDetectorRef.

constructor(private chRef: ChangeDetectorRef){

    let temp = store.select(fromRoot.getIconDetail);

    temp.subscribe((d)=>{
        this.data = d;
        this.chRef.detectChanges();
    });
}

I am not sure if this is the right way but I am unable to figure out whats going on or any other solution.

Any help will be greatly appreciated. Thanks


Solution

  • This is what I finally did. Would love someone to post a better solution. Thanks to Stephen for the unsubscribe suggestion.

    constructor(private ngZone: NgZone){
        store.select(fromRoot.getIconDetail)
        .takeUntil(ngUnsubscribe)
        .subscribe((d)=>{
            this.ngZone.run(() => {
                this.someFunction(d);
            });
        });
    }