Encountering an Angular 6 issue that involves waiting for promises to be resolved before proceeding. The code below successfully demonstrates this functionality:
AppService.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class AppService {
p1: Promise<any>;
p2: Promise<any>;
constructor() {
this.getPromise1();
this.getPromise2();
}
getPromise1() {
this.p1 = new Promise((resolve, reject) => {
resolve(true);
});
}
getPromise2() {
this.p2 = new Promise((resolve, reject) => {
setTimeout(() => resolve(true), 5000);
});
}
}
AppComponent.ts
import { Component, AfterViewInit } from '@angular/core';
import { AppService } from './app.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {
constructor(private appSrvc: AppService) { }
ngAfterViewInit(){
Promise.all([this.appSrvc.p1, this.appSrvc.p2])
.then(values => {
console.log(values);
//Execute additional logic if all promises are resolved
})
.catch(error => {
console.log(error.message)
});
}
}
However, when attempting to make a similar setup using a timeout event in the initialize method of AppService.ts as shown below, the promises fail to work:
AppService.ts
constructor() {
this.initialize();
}
initialize(){
setTimeout(() => {
this.getPromise1();
this.getPromise2();
}, 1000);
}
...
The above implementation does not behave as expected, and I am seeking assistance in understanding why. Any help would be greatly appreciated.
Thank you!