How to stop a method in Angular2 when a specific response is received?

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.

Answer №1

If you want to filter data based on a condition in RxJS, you can make use of the takeWhile operator:

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

This operator emits values emitted by the source Observable as long as each value satisfies the provided predicate function. It completes as soon as the predicate function returns false for a value.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is Angular 10 disregarding set-cookie response headers?

After logging in, I attempted to utilize a session auth cookie without success. To troubleshoot, I implemented a basic "CookieTest" method on my Dotnet Core server: [Route("CookieTest")] public ActionResult CookieTest() { var options = new CookieOptions ...

The NGX-Datatable is showing certain numerical values as 'Infinity'

I'm currently investigating why I keep seeing the word 'Infinity' displayed for certain values in my table. For instance, one of the columns is labeled 'Bill To' and has a value of '20E7543' as a string. Despite confirmi ...

Obtain a value that is not defined

Good day, I am encountering an issue with my data not accepting an undefined value. Below is the code snippet: interface IModalContatos { dados: IContatos; onSave(dados: IContatos): void; onClose(): void; } When passing this data to my modal, I rece ...

reactjs: disable a specific eslint rule

I'm trying to figure out how to disable the "no-unused-vars" rule specifically for TypeScript interfaces. Here's a code snippet where I'm getting a warning: export type IKeoTableColumn<T> = { id: T; align: 'left' | ' ...

TypeScript generic type and potential absence of a value

Recently, I've been delving into Facebook's immutable library and exploring their TypeScript bindings. Consider this snippet of code: const list: User[] = ...; list.map(user => ...) The lambda parameter user correctly has the type of User. ...

Issue with Angular: boolean value remains unchanged

Currently, I'm encountering an issue with my application. My objective is to establish a list containing checkboxes that toggle their values between true and false when clicked. Sounds simple enough, right? Below is the HTML code snippet: <l ...

Ways to receive one of two variations

Dealing with different cases for type is my current challenge. In a React Functional Component, I have a callback function property that accepts an argument of either string or number. interface InputProps { getValue?: (value: string | number) => vo ...

Similar to AngularJS Component's "require" property, Angular Component also has an equivalent

In the process of updating a sizable Angular 1.6 App, we encounter numerous components that utilize 'require' to access the parent component's controller. The structure of an AngularJS component appears as follows: var tileTextbox = { ...

The functionality of Angular 2 md-radio buttons in reactive forms seems to be hindering the display of md-inputs

Currently, I am following the instructions for implementing reactive form radio buttons on a project using Angular 2.1.2 and Google's MD-alpha.10 Atom-typescript shows no errors in my code. However, when testing the application, I encountered the foll ...

Lazy loading child routes in Angular 4 encounters issues when the child routes share the same path

I have developed an application that features a contact list with the capability to select and view detailed information about a single contact. The contact detail page includes tabs for sub-information such as profile, touch points, and contact info. Belo ...

Incorporating dynamic dependency injection in Angular 2 through the use of @Input()

Let's consider a scenario where an Angular 2 component-directive needs to dynamically determine the injected dependency it uses based on an @Input(). For example, I would like to be able to specify <trendy-directive use="'serviceA'"> ...

TSX implementation of a paginator with an ellipse in the center

Looking to add ellipses in the Pagination, specifically when there are more than 10 pages (e.g., 1 2 3 4 ... 11 12 13 14). I've tried various methods but need guidance as a beginner. Can anyone suggest changes based on my code to help me achieve this? ...

Posting an array as form data in Angular Typescript: A step-by-step guide

Hello there, I'm currently developing an application using Angular 8 and integrating web.api within .net core 2.2. One of the challenges I encountered is dealing with multi-selectable checkboxes in a form that also includes "regular" inputs and file ...

Issues with Cross-Origin Resource Sharing (CORS) have been identified on the latest versions of Android in Ionic Cordova. However, this problem does not

I am encountering an issue with my TypeScript Ionic code. It works well in browsers and some older mobile devices, but it fails to function on newer Android versions like 8+. I need assistance in resolving this problem. import { Injectable } from '@an ...

Ensuring strictNullChecks in Typescript is crucial when passing values between functions

When using the --strictNullChecks flag in TypeScript, there seems to be an issue with inferring that an optional property is not undefined when the check occurs in a separate function. (Please refer to the example provided, as articulating this clearly is ...

Compile time extraction of constant string from type field

I am currently facing an issue with a field in my type that contains a constant string literal. My goal is to be able to reference both the type and field by name so that I can utilize this string literal throughout my code. Here is an example: export type ...

How to dynamically retrieve values from a const object literal using TypeScript

Currently, I am utilizing a TypeScript library known as ts-proto, which is responsible for generating TypeScript code. The resulting generated code resembles the following: //BasicMessage.ts export interface BasicMessage { id: Long; name: string; } ...

What is the best way to handle waiting for an HTTP request to complete from a separate component?

https://i.sstatic.net/q4XYB.png An issue arises when calling the GetData function from a component's controller too early. I would like it to wait for the identification process to complete before triggering. During page loading, there is a server c ...

Would it be frowned upon to rely on store instead of data binding for inter-component communication when accessing my data?

Within my current framework, I house the primary business logic within selectors and effects. Components are able to request data by triggering an action that queries the necessary information through selectors. Apart from instances where *ngFor is utili ...

Connect the Result of a Button Click to a Fresh Span

Just starting out with Angular2 so I'm keeping things simple for now. I understand the importance of separating feature components, but my main focus at the moment is getting everything to function properly. My objective here is to bind the value of ...