rhysclay
rhysclay

Reputation: 1683

Angular2 Observable Callback

Im trying to implement a simple callback once an observable has finished, here is my code:

ngOnInit() {
    this.propertyService
    .getProperties()
    .subscribe(
        (data: ContentPropertyModel[]) => this.properties = data
    );
    this.status = 'active';
}

However the status is changed before the observable runs. Any ideas on how i can changes the this.status after the observable runs?

Upvotes: 4

Views: 6580

Answers (3)

user663031
user663031

Reputation:

Yes, as pointed out in another answer, you must set status within the subscribe handler. However, this also means that status is not set at all until the observable emits its first item. I'd suggest as an alternative making status an observable itself, which you can accomplish with something like

this.status$ = this.propertyService.getProperties()
  .startWith(false)
  .map(b => b ? 'active' : 'waiting');

Now in your template to display status

STATUS IS {{status$ | async}}

And the display will be waiting until the observable first fires.

If you should need to access the current value of status in an event handler, you can do so with

logStatus() {
  this.status$.take(1).subscribe(s => console.log("status is", s);
}

If you treat properties in the same way, as an observable,

ngOnInit() {
  this.properties$ = this.propertyService.getProperties();
  this.status$ = this.properties$.startWith(false).map(b => b ? 'active' : 'waiting');
}

then you can avoid altogether subscriptions in your ngOnInit which will need to be remembered and then torn down in ngOnDestroy.

Upvotes: 1

Sekar
Sekar

Reputation: 387

Subscribe takes in three arguments(OnNext function, Error Function, Completed Function).

If you want to run your code to run after each item is received then code in the first function argument. If you want to run after the completion of the stream then code in the last function argument.

ngOnInit() {
    this.propertyService
    .getProperties()
    .subscribe(
        (data: ContentPropertyModel[]) => {
            this.properties = data
        },
        (err) => console.log(err),
        () => this.status = 'active'
    );
}

Refer this link http://reactivex.io/documentation/observable.html.

Also onError() and Completed() function wont work for DOM events.

Upvotes: 4

Michael Kang
Michael Kang

Reputation: 52847

Move this.status to your subscribe handler:

ngOnInit() {
    this.propertyService
    .getProperties()
    .subscribe(
        (data: ContentPropertyModel[]) => {
            this.properties = data
            this.status = 'active';
        }
    );
}

Upvotes: 5

Related Questions