I've been grappling with the idea of unsubscribing from a method in Angular2 once it receives a specific response.
settings.component.ts
Within my component, the method in question is connectToBridge, where the value of this.selectedBridge is a string representing an IP address.
public connectToBridge() {
this._hueService.connectToBridge(this.selectedBridge)
.subscribe(bridgeResponse => { this.bridgeResponse = bridgeResponse });
}
bridgeresponse.model.ts
This model is being mapped in 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());
});
Currently, I'm using an observable to continuously check the API endpoint every 2 seconds for a different response. Is there a more efficient approach for this? Essentially, once the success value inside the model is not null, I'd like to unsubscribe from the method and halt the 2-second polling.
On a side note, I'm using .NET Core and WebApi to develop the API.