Charlie.H
Charlie.H

Reputation: 479

Unsubscribing from an Angular2 method when a certain response is given?

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.

Upvotes: 4

Views: 653

Answers (1)

n00dl3
n00dl3

Reputation: 21564

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);
}

Upvotes: 3

Related Questions