Home > OS >  Typescript execute function after two subscriptions return
Typescript execute function after two subscriptions return

Time:03-09

I have two subscriptions to services. I need to run code after both of these subscriptions return all records. How do I accomplish this?

Here is the relevant current code current in ngOnit

this.userService.get$(this.userId).subscribe(
  u => this.user = u);

  this.roleService.getAll$().subscribe(
    r => this.roles = r);

CodePudding user response:

You have to use concat from rxjs to execute your Observable in sequence.

import { concat } from 'rxjs';    
concat(
    this.userService.get$(this.userId).subscribe(
    u => this.user = u);

    this.roleService.getAll$().subscribe(
    r => this.roles = r);
    )
.subscribe(console.log);

CodePudding user response:

Use forkJoin for that - this will execute both request in parallel

forkJoin({
user:this.userService.get$(this.userId).subscribe(u => this.user = u),
roles:this.roleService.getAll$()
}).subscribe(results=>{
    this.user=results.user;
    this.roles=results.roles;
    //do whetever has to be done here since both are complete
})

CodePudding user response:

You can use promise for this task, to see documentation click here

var first = new Promise((resolve, reject) => {
    this.userService.get$(this.userId).subscribe(u => {
        this.user = u
        resolve(u)
    });
});

var second = new Promise((resolve, reject) => {
    this.roleService.getAll$().subscribe(r => {
            this.roles = r
            resolve(r)
        });
});

Promise.all([first, second]).then((values) => {
    console.log(values);
});
  • Related