Ways to retrieve a value from outside the Angular subscribe block

Custom Template

<div class="row" *ngFor="let otc of this.jsonData;index as j">
        <div>
            <table class="table table-striped table-fixed">

    <tr *ngFor="let opc of this.winServiceInfo(j);index as i">

Typescript Code

ngOnInit(): void {
    this.geWinService();
}

winServiceInfo(j: number) {
    this.winServiceURL = JSON.parse(this.WinService[j].windowsServicesInfo)["Stactuscheck"];
    this.dataArrs = [];
    this.service.getWinServicesInfo(this.winServiceURL)
      .pipe(
        catchError(this.handleError)
      )
      .subscribe(
        (data: any) => {
          this.setSubscribeData(data);
          console.log(this.dataArrs);
          return this.dataArrs;
        });
    console.log(this.dataArrs);
    return this.dataArrs;
}

setSubscribeData(data): any {
    this.WinService = data.windowsServicesInfo;
    this.dataArrs = this.getKeyValJsonObj();
    return this.dataArrs;
}

getKeyValJsonObj() {
    this.dataArr = [];
    for (let key of this.sliceIntoChunks()) {
      for (let i in key) {
        this.dataArr.push({ 'key': i, 'value': key[i] });
      }
    }
    return this.dataArr;
}

The first console.log(this.dataArrs) in the winServiceInfo method returns Array(3), but the second console.log(this.dataArrs) returns Array(0). This is due to the asynchronous nature of the subscribe operation.

To handle this situation and return Array(3) from the second console.log(this.dataArrs), you can use callback functions or Promises to ensure that the data retrieval is completed before returning the result.

Answer №1

Firstly, it is strongly advised to avoid using a function call like this directly in HTML.

Executing the function at every change detection can lead to severe performance issues. Moreover, if HTTP calls are involved, it could quickly deplete someone's data plan.

Secondly, it is recommended to refrain from utilizing this excessively. It is best practice to limit variables to their respective scopes.

Instead, consider creating an observable for observation:


data$ = forkJoin(
  this.jsonData.map(j => {
    const winServiceURL = JSON
      .parse(this.WinService[j].windowsServicesInfo)["Stactuscheck"];

    return this.service.getWinServicesInfo(this.winServiceURL);
  }).pipe(
    switchMap(data => {
      const WinService = data.windowsServicesInfo;
      const dataArr = [];
      for (let key of this.sliceIntoChunks()) {
        for (let i in key) {
          dataArr.push({ 'key': i, 'value': key[i] });
        }
      }
      return dataArr;
    })
  )
)

Incorporate the following snippet in your HTML markup:

<div class="row" *ngFor="let opc of data$ | async">
  {{ opc | json }}
</div>

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

The test() function in JavaScript alters the output value

I created a simple form validation, and I encountered an issue where the test() method returns true when called initially and false upon subsequent calls without changing the input value. This pattern repeats with alternating true and false results. The H ...

Triggering multiple updates within a single method in Angular will cause the effect or computed function to only be triggered

Upon entering the realm of signals, our team stumbled upon a peculiar issue. Picture a scenario where a component has an effect on a signal which is a public member. In the constructor of the component, certain logic is executed to update the signal value ...

Guide on creating a Jasmine test for a printer utility

Currently, I am working on writing a Jasmine test for the print function shown below: printContent( contentName: string ) { this._console.Information( `${this.codeName}.printContent: ${contentName}`) let printContents = document.getElementById( c ...

Angular 4 project occupying significant disk space

After discovering that my Angular 4 project takes up approximately 300 MB on disk, I realized that the node_modules folder is to blame for this large size. Would it be advisable to exclude this folder from the repository in order to save space and reduce d ...

Display different icons in an Angular application based on the value received from an API in real

My goal was to create a dynamic form that displays icons for the fields I have created. Here is a snapshot of my UI screen showing the field explorer with the list coming from an API. https://i.sstatic.net/4Ye9G.png I need to place an icon in front of ea ...

Utilizing Generic Types in React TypeScript Functional Components

I'm currently developing a TypeScript React component that includes generic type props, so I define the React component as: export interface MyCompProps<T> { items: T[]; labelFunction: (T) => string; iconFunction: (T) => JSX.Element; ...

Angular 2 Routing 3.0: Paying Attention to Letter Case

let routesList: Routes = [ { path: 'x', component: xComponent }, { path: 'y', component: yComponent }, { path: 'zComponent', component: zComponent } ]; When entering "x" in the URL, it navigates to the component page. Ho ...

Is there a way to verify if an object adheres to a specified interface?

Let's say I have a custom interface called MyInterface Is there a built-in method in TypeScript that allows checking if an object adheres to the MyInterface ? Something similar to using instanceof but for interfaces instead of classes. ...

Issue with Angular 7 Universal: components inside are failing to display

I have successfully implemented Angular 7 Universal with dynamic server-side rendering. However, I am facing an issue where dynamic components within the main component being rendered on the server are not rendered themselves. Here is an example of the re ...

Enhancing a Given Interface with TypeScript Generics

I am looking to implement generics in an Angular service so that users can input an array of any interface/class/type they desire, with the stipulation that the type must extend an interface provided by the service. It may sound complex, but here's a ...

Tips for tidying up duplicated typescript content sourced from a pre-existing library

Seeking guidance on implementing best practices and gaining a better understanding of my approach. After discovering the library react-google-calendar-api, I successfully installed it using npm in my React project. However, I wanted to expand its function ...

Node.js built-ins require shims, while global variable names are absent

After updating my project using npm-check-updates, I encountered a strange error that stumped me. Despite following the suggested terminal command to install polyfill-node, the issue persisted with no resolution in sight online. The error displayed on the ...

Steps for configuring Types in Graphql Codegen

I have successfully implemented a Vue 3 component that utilizes Urql to query a Hasura graphql endpoint. The query is functioning properly, but I am now focused on enhancing the type safety of the component. My approach involves using graphql Codegen to g ...

Updating Angular 7 ngrx state management without the need for explicit action types

After calling an ngrx action and saving the result in a local variable within a component, I noticed that if I edit this copy without saving it as well as taking any specific actions, when I leave the route, the store is automatically updated! Here is a s ...

Retrieve selected button from loop typescript

https://i.stack.imgur.com/DS9jQ.jpgI have an array of individuals that I am looping through. It's a bit difficult for me to explain, but I want something like this: <div *ngFor="let person of persons"> {{person.name}} {{person.surname}} <but ...

Although everything appears to be running smoothly in Express, my request is returning null

I am facing an issue with a router in my code. In the main index.ts file, I have the following line: app.use("/api/tshirts", tshirts) And in tshirts.ts file, I have defined the following routes: router.get("/", tshirtsController.getTShirts) router.get("/ ...

Utilizing Dynamic Class Names in Angular 7 with Typescript

In the process of developing an Angular 7 application, I have created a form component that is intended to be used for various entities. As part of this, I defined a variable route: {path: ':entity/create', component: FormComponent} While this ...

Chai expect() in Typescript to Validate a Specific Type

I've searched through previous posts for an answer, but haven't come across one yet. Here is my query: Currently, I am attempting to test the returned type of a property value in an Object instance using Chai's expect() method in Typescript ...

Error in Typescript: 'SyncClient' not found in Twilio

While working on my Ionic app, I encountered an issue every time I attempted to use the twilio-chat library in my project through npm install. The error consistently appeared in the .d.ts files. Here is how I imported it in my provider : import { Client ...

Utilizing a React npm component within an Angular project: A step-by-step guide

After successfully creating a simple react component and publishing it to the NPM registry, I encountered an issue when trying to use the same plugin in an Angular project. The custom plugin can be found at: https://www.npmjs.com/package/reactcustomplugin ...