Search code examples
angularpromise

How to call two methods in Angular ngOnInit, one after other


I have two methods in ngOnInit. The other need the data from first. Both are calling rest service observable methods.

ngOnInit(){
    this.one().then(userId => this.two(userId));
}

How to write these methods so that 'then' chaining works, returning a Promise object?

one(){
    restService.getUserId().subscribe(       
        resp => {
            userId: number = resp.result;
        }
    )
}

two(userId: number) { 

restService.getData(userId).subscribe(resp => {
        adress: string = resp.result;
    }
    
    )
    }

Solution

  • If you want to work with then, turn the observables into promises, and make sure to return them.

    one() {
        return restService.getUserId().toPromise().then(resp => resp.result);
    }
    
    two(userId: number) {
        return restService.getData(userId).toPromise().then(resp => resp.result);
    }
    
    ngOnInit(){
        this.one().then(userId => this.two(userId))
                  .then(userData => { /* do something with the data */ });
    }