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.