Is it possible to evaluate a conditional in Angular after retrieving values from a subscription in an observable?

Objective: Verify conditional statement after retrieving data from an array

Attempts Made: I explored various articles on SO with similar queries, but they didn't quite match my situation. I need to ensure that the entire Array is populated before evaluating the IF condition.

I experimented with moving the IF condition inside the subscription, however, it resulted in multiple calls.

Debugger Feedback: The process goes smoothly from the getV() call to the method, but upon reaching the first subscribe, it loops back to the IF statement.

Typescript Code:

    ngOnInit {
     this.getV(vId);
     if (this.internalNotes.length > 0) {
              this.dialog.open(DialogInternalNotesThreeComponent, {
                  data: {
                      data: this.internalNotes
                  }
              });
          }
      
    }

    public getV(vId: number) {
        this.vs.V(vId)
            .subscribe(resp => {
                this.ps.GetPInternalNotes(resp.PID.toString()).subscribe(respPIN => {
                    for (let index = 0; index < respPIN.length; index++) {
                        this.internalNotes.push(respPIN[index]);
                        
                    }
                });
            });         
    }

UPDATE: Placing the IF statement immediately after the FOR loop in the subscribe block seems to prevent duplicate dialogs. Does this implementation appear correct?

public getV(vId: number) {
        this.vs.V(vId)
            .subscribe(resp => {
                this.ps.GetPInternalNotes(resp.PID.toString()).subscribe(respPIN => {
                    for (let index = 0; index < respPIN.length; index++) {
                        this.internalNotes.push(respPIN[index]);
                    }
                    if (this.internalNotes.length > 0) {
                        this.dialog.open(DialogInternalNotesThreeComponent, {
                            data: {
                                data: this.internalNotes
                            }
                        });
                    }
                });
            });         
    }

Answer №1

Observing observables can be misunderstood at times. The code does not always run synchronously, as in a line-by-line fashion, which is the core concept of reactive programming.

this.getV(vId);
if (this.internalNotes.length > 0)

When we reach the if statement, the array may not be fully initialized yet because the observable might not have pushed respPIN[index] into the array.

This explains why placing it right after the FOR loop within the subscribe function helps resolve multiple dialogs popping up.

If you wish to maintain this behavior, consider returning an observable of the array inside your getV() method.

ngOnInit {
  // Subscribe to the returned array
  this.getV(vId).subscribe(
       (internalNotes) => {
            if (internalNotes.length > 0) {
                this.dialog.open(DialogInternalNotesThreeComponent, {
                    data: {
                        data: internalNotes
                    }
                });
              }
        });
 }

 // Method that returns an observable containing the array
 public getV(vId: number): Observable<Array<any>> {
     this.vs.V(vId)
         .subscribe(resp => {
             this.ps.GetPInternalNotes(resp.PID.toString()).subscribe(respPIN => {
                 for (let index = 0; index < respPIN.length; index++) {
                     this.internalNotes.push(respPIN[index]); 
                 }
                 // Return an observable with the current array
                 return of(this.internalNotes);
             });
         });

    // Base case: return an empty observable  
    return EMPTY;       
 }

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

Encountering a service error that results in the inability to read properties of undefined when passing a method as a

Whenever I attempt to pass a service function as a parameter to another function, an error 'Cannot read properties of undefined myService' occurs during execution. However, calling this.myService.method() individually works perfectly fine without ...

How can I create interfaces for deeply nested objects in TypeScript?

Check out my current JSON data below: { "state_1": { "date": [ { 1000: { "size": 3, "count": 0 } }, { 1001: { "size" ...

Error in main.ts due to issues with importing components using an index.ts file

I am facing a common exception: Unexpected directive value 'undefined' on the View of component 'AppComponent' Many solutions I found online did not address my specific issue related to circular dependencies or missing export statem ...

Issue with comparing strings in Typescript

This particular issue is causing my Angular application to malfunction. To illustrate, the const I've defined serves as a means of testing certain values within a function. Although there are workarounds for this problem, I find it perplexing and woul ...

What is the proper way to integrate helmet.js with typescript?

Utilizing helmet from pure JavaScript according to the documentation is quite straightforward: const express = require('express') const helmet = require('helmet') const app = express() app.use(helmet()) However, I'm unsure how ...

Guide: Ensuring the validity of an object retrieved from a database with Nest.js class-validator

When activating a user, I need to ensure that certain optional data in the database is not empty by using class-validator dto. So far, my controller level validations for body, query, and all other aspects have been successful. The DTO file contains vali ...

Using TypeScript's `extend` keyword triggers an ESLint error when attempting to extend a generic type

I am dealing with numerous models that include additional meta data, which led me to create a generic type for appending them to the models when necessary: type WithMeta<T> = T extends Meta; However, I encountered an error stating: Parsing error: &a ...

Clear drop down selections after button is pressed

I am currently working with a grid in my template that contains multiple dropdowns, each row having its own. When I click a button, I gather the values from these dropdowns. However, upon clicking this button, I wish to reset all the dropdowns back to thei ...

How should one properly assign an element type provided as an argument?

I'm attempting to define a type for an element passed as a parameter using React.ComponentType. import * as React from "react" type BaseType = { element: React.ComponentType } const Base = ({element: Element}: BaseType) => ( <Ele ...

What type of value does a `use` directive return?

Upon reviewing the svelte tutorial, I observed that the clickOutside function provides an object with a destroy method. What should be the precise return type of a custom use directive? export function clickOutside(node: HTMLElement): ??? { // Initia ...

Webpack is struggling to locate core-js paths when running on Windows operating systems

When running webpack, I am encountering the following errors: ERROR in ./node_modules/core-js/index.js Module not found: Error: Can't resolve './es' in 'pathtoproject\node_modules\core-js' @ ./node_modules/core-js/index. ...

Encountering difficulties when attempting to globally install Angular CLI on Node.js version 18.15.0

Encountering an issue while setting up the latest version of Angular using NVM and the most recent Node.js version After installing Node.js version 18.15.0, I attempted to run npm i -g @angular/cli Unfortunately, I received the error below. Has anyone el ...

React throwing an error when trying to use inline fontWeight styling with Typescript

I am currently working on applying a CSS rule to a td element. const boldText = { fontWeight: 'bold' } <td style={boldText}>Content</td> Unfortunately, I am encountering the following error: [ts] Type '{ style: { fontWeig ...

The variable "this.data" in Angular 2 is experiencing the issue

I am attempting to access and read the information stored in my JSON file using my "GetJsonService". app.component.ts: data: any; constructor(private jsonService: GetJsonService) {} ngOnInit() { this.getRecords(); console.log(this.data); } get ...

Using Owl Carousel 2 and other jQuery plugins in Angular 4 TypeScript classes: A step-by-step guide

I have been facing challenges trying to incorporate jQuery plugins into an Angular 4 TypeScript class. Despite multiple attempts, I have not been able to achieve my goal. I tried various methods, but the HTML component view in Angular 4 does not seem to s ...

A guide on implementing a "Select All" trigger in mat-select with Angular8/Material

Here is the code I have created: <mat-form-field appearance="outline"> <mat-label>Handler Type</mat-label> <mat-select multiple [(value)]="handlerType"> <mat-option *ngFor="let handler of handlerT ...

Modifying the color of a variety of distinct data points

There was a previous inquiry regarding Changing Colour of Specific Data, which can be found here: Changing colour of specific data Building upon that question, I now have a new query. After successfully changing the 2017 dates to pink, I am seeking a way ...

Encountering a CORS issue when utilizing passport-facebook for Facebook authentication in my MEAN application

I'm currently working on implementing a Facebook login feature for my web app, built with express js, mongodb, and angular 2. The client-side of the app is generated using angular-cli (running on port 4200), and I'm utilizing the proxy config pr ...

The attribute 'checked' is not a valid property for the 'TElement' type

Learning about typescript is new to me. I have a functional prototype in fiddle, where there are no errors if I use this code. http://jsfiddle.net/61ufvtpj/2/ But in typescript, when I utilize this line - if(this.checked){ it presents an error [ts] Pro ...

What could be causing the issue with the variable appearing as undefined in

My class has a property: public requestLoadPersonal: Personal[] = []; As well as a method: private filterByGender(selectedValue: any): void { console.log(this.requestLoadPersonal); this.requestLoadPersonal = this.requestLoadPersonal.filter( ...