Ad

Await For Promise Before Give The Result As Input Parameter

I have two components parent and child

parent is resolving a promise in constructor, child is reveiving the result of the promise as @Input() parameter

child is not receiving the result of the promise in life cicle hook other than afterViewCheck and afterContentCheck, I want to avoid those.

I also want to avoid a shared service containing shared data in behaviorSubject or something like that

so the question is, can I await the promise before construct the template with te result of the promise as an input parameter?

Parent:

// html: <app-chil [brands]="brands"></>

brands: Brand[] = []

constructor() {
  this.getBrands()
}

async getBrands() {
  this.brands = await new Promise<Brand[]>(resolve => 
    this.equipmentService.getBrands().subscribe(brands => resolve(brands)))
}

child:

@Input() brands: Brand[] = []

constructor() { }

ngAfterViewInit() {
  console.log(this.brands) // receive brands here
}
Ad

Answer

With a setter, you dont need to use any life cycle hook and its cleaner.

brands: Brand[] = [];

constructor() {
   this.getBrands()
}

async getBrands() {
  this.brands = await new Promise<Brand[]>(resolve => 
    this.equipmentService.getBrands().subscribe(brands => resolve(brands)))
}

child:

private _brands: Brand[] = [];
@Input() set brands(data: Brand[]) {
    this._brands = data;
    console.log(data);
}

constructor() { }
Ad
source: stackoverflow.com
Ad