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

When transitioning between views in Angular App, it freezes due to the large data response from an HTTP request

I am encountering an issue with my Angular 9.1.11 application where it freezes after navigating from one page to another (which belongs to a different module with lazy loading). Here is the scenario: There is an action button called View Report that re ...

Angular's CanActivate feature fails to navigate to a new route upon calling the refresh token API, even if it returns true

I have been implementing route guard and token interceptor in an Angular 6 project. Within the route-guard's canActivate method, there is an async function that verifies whether the access token has expired: If it has expired, the system checks i ...

Utilizing ALERTIFY JS (v1.9.0) with Angular 2: Step-by-Step Guide

I am having trouble implementing AlertifyJS (v1.9.0) in my Angular 2 application. In the vendor.ts file, I have included the following: import "alertifyjs/build/alertify.min.js"; import "alertifyjs/build/css/alertify.min.css"; and made a call to alertify ...

What is preventing type guarding in this particular instance for TypeScript?

Here is an example of some code I'm working on: type DataType = { name: string, age: number, } | { xy: [number, number] } function processInput(input: DataType) { if (input.name && input.age) { // Do something } e ...

Alert: User is currently engaging in typing activity, utilizing a streamlined RXJS approach

In my current project, I am in the process of adding a feature that shows when a user is typing in a multi-user chat room. Despite my limited understanding of RXJS, I managed to come up with the code snippet below which satisfies the basic requirements for ...

Having issues with jsonConvert.deserializeObject not functioning in angular2 json2typescript

Greetings, I am new to Angular 2 and working on fetching user data from Google, Facebook, and LinkedIn. I am attempting to deserialize an object into an instance of a class I created named UserLogin, but unfortunately it does not seem to be working. Here ...

Encountering build errors with @angular/cdk and @angular/forms post updating to Angular 11

Upon upgrading to Angular 11, I encountered a series of errors during the build process of my solution: \node_modules\@angular\cdk\coercion\array.d.ts(10,60): error TS1005: Build:',' expected. \node_modules\@ang ...

Best Practices for Variable Initialization in Stencil.js

Having just started working with Stencil, I find myself curious about the best practice for initializing variables. In my assessment, there seem to be three potential approaches: 1) @State() private page: Boolean = true; 2) constructor() { this.p ...

Installation of ag-grid was unsuccessful

Having trouble with this command and error message, any suggestions on how to resolve it? npm install --save ag-grid-community ag-grid-angular https://www.ag-grid.com/angular-grid/getting-started/ ...

Using formControlName with an Ionic2 checkbox allows for seamless integration of

Currently facing an obstacle with checkboxes in ionic2. Here is how I am using the checkbox: <ion-item> <ion-label>Agree</ion-label> <ion-checkbox color="dark" id="agree" name='agree' class="form-control" formContro ...

The storybook is struggling to find the correct builder for the Angular project

I have set up a complex angular workspace with multiple projects. Within the main angular workspace project directory, I have two folders - one for the project application named eventric, and another for a library called storybook. https://i.stack.imgur.c ...

The Angular component seems to be failing to refresh the user interface despite changes in value

Recently, I created a simple component that utilizes a variable to manage its state. The goal is to have the UI display different content based on changes in this variable. To test this functionality, I implemented the component and used a wait function to ...

Resolving "SyntaxError: Unexpected identifier" when using Enzyme with configurations in jest.setup.js

I'm currently facing an issue while trying to create tests in Typescript using Jest and Enzyme. The problem arises with a SyntaxError being thrown: FAIL src/_components/Button/__tests__/Button.spec.tsx ● Test suite failed to run /Users/mika ...

Angular: Display a null value retrieved from an asynchronous data source

When retrieving data from the backend (Node.js/Express.js + Oracledb), there are null values present. I need to display "Null" in the HTML table wherever these null values exist. Is there a way to achieve this? This is my code: .component.html <div cl ...

Steps to fix the issue of 'Property 'foo' lacks an initializer and is not definitely assigned in the constructor' while utilizing the @Input decorator

What is the proper way to initialize a property with an @Input decorator without compromising strict typing? The code snippet below is triggering a warning: @Input() bar: FormGroup = new FormGroup(); ...

Issues with date clicking on FullCalendar in Angular

I'm currently using version 4.4.0 of the FullCalendar plugin, but I am facing an issue where the dayClick event is not being triggered in my code. Below is a snippet of my code: calendar.component.html <full-calendar defaultView="dayGridMonth ...

Encountering difficulties with Bootstrap toggle functionality in Angular 2.0 following the establishment of a MEAN stack

While setting up a MEAN stack app following a tutorial, everything was going smoothly until I decided to test some Bootstrap components from their site. After installing Bootstrap in the index.html file for Angular, I noticed that Bootstrap was being loade ...

Is there a way to change routerLink to href?

I am struggling with converting routerLink to href. <a [routerLink]="['/choose',{id:sizzle.parameter,type:dish}]" I attempted it, but I keep getting an error <a [href]="'/choose'+id:sizzle.parameter+type:dish" ...

Is there a way to prevent the Drop event in Angular2?

In my Angular2 application, I have created a directive for an input field. To prevent paste or Ctrl+V within the host element of this directive, I used the following code which is functioning flawlessly: @HostListener('paste', ['$event&apos ...

Customizing the renderInput of the Material UI DatePicker

Recently I integrated material-ui into my React project with TypeScript. I implemented the following code based on the example provided on the official website. import AdapterDateFns from '@mui/lab/AdapterDateFns'; import DatePicker from '@m ...