Angular assign value inline in click from an async function

193 Views Asked by At

I have a pretty unique situation of assigning value to a variable inline using click event via an async function call. I have ng-template-for where a deeply nested and complex set of object is rendered on screen(e.g. comment of comment of comment and so on). So it is not possible to take the object and assign value by key or id once the function returns.

<button (click)="c.state = callState(c) ">Check</button>

Function is as follows:

async callState(c:any){
 let a = await http.call();
 return  Promise.all([a]);
}

Other 2 function variations return the same results:

   async callState(c:any){
     await http.call().then((res:any)=>{
       return res.
      });
    }

async callState(c:any){
 let a = await http.call();
 return  a;
}

I have tried many different variations of this, but the component view always get [object Promise]. It is supposed to pass a string. On inspection, the value is :

ZoneAwarePromise
__zone_symbol__state: true
__zone_symbol__value: [{…}]

Can someone help to assign a string from a simple http call inline on click to a view variable?

1

There are 1 best solutions below

0
Satish Umagol On

ts file

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'projecttest';
  public c: any = {};

  constructor(private http: HttpClient) { }

  async updateState(c: any) {
    const result: any = await this.callState(c);
    // Assuming the result is an array, update index accordingly
    return result[0].title;
  }

  async callState(c: any) {
    const a = await this.http.get('https://jsonplaceholder.typicode.com/todos/1').toPromise();
    return Promise.all([a]);
  }
}

html template

<button (click)="c.state = updateState(c)">Check</button>
<div>{{ c?.state |async }}</div>

In your component, the updateState method now directly assigns the resolved value to c.state. Then, in your template, you're using the AsyncPipe to automatically unwrap and display the value of c.state once it's resolved.