4

I'm trying to get my head around how I can unsubscribe from a method in Angular2 when the method gets a certain response.

settings.component.ts

This is the method in question inside my component, the value of this.selectedBridge is just a string with an IP address as the value.

public connectToBridge() {
    this._hueService.connectToBridge(this.selectedBridge)
        .subscribe(bridgeResponse => { this.bridgeResponse = bridgeResponse });
}

bridgeresponse.model.ts

This is the model which I'm mapping to inside my hue.service.

export interface BridgeResponse {
    error: Error;
    success: Success;
}

export interface Error {
    type: string;
    address: string;
    description: string;
}
export interface Success {
    username: string;
}

hue.service.ts

connectToBridge(bridgeIp) {
    return Observable.interval(2000).flatMap(() => {
        return this.http.post('http://localhost:54235/api/hue/ConnectToBridge',
                JSON.stringify(bridgeIp),
                { headers: this.headers })
            .map(response => <BridgeResponse>response.json());
    });

As you can see I'm using an observable to keep polling the API endpoint every 2 seconds to check if the response has changed, is there a better way of doing this? Essentially when the value of success inside the model is not null, I want to unsubscribe from the method and stop it polling every 2 seconds.

Also, just as some extra information I'm using .NET Core and WebApi to build the API.

Charlie.H
  • 469
  • 2
  • 9
  • You need also to unsubscribe your subscription in `ngOnDestroy()`. [This post](http://stackoverflow.com/questions/38008334/angular2-rxjs-when-should-i-unsubscribe-from-subscription) has a better alternative to unsubscribe than to directly unsubscribe the subscription. – andreim Apr 24 '17 at 17:15

1 Answers1

3

You can use takeWhile :

public takeWhile(predicate: function(value: T, index: number): boolean): Observable<T>

Emits values emitted by the source Observable so long as each value satisfies the given predicate, and then completes as soon as this predicate is not satisfied.

connectToBridge(bridgeIp) {
    return Observable.interval(2000).switchMap(() => {
      return this.http.post('http://localhost:54235/api/hue/ConnectToBridge',
          JSON.stringify(bridgeIp), {
            headers: this.headers
          })
        .map(response => < BridgeResponse > response.json());
    }).takeWhile(data=>data.success===null);
}
n00dl3
  • 21,213
  • 7
  • 66
  • 76