Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript execute function after two subscriptions return

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);
like image 542
Abraham Lincoln Avatar asked Sep 05 '25 03:09

Abraham Lincoln


2 Answers

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

forkJoin({
user:this.userService.get$(this.userId),
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
})
like image 88
Antoniossss Avatar answered Sep 07 '25 21:09

Antoniossss


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);
});
like image 31
Zulqarnain Jalil Avatar answered Sep 07 '25 21:09

Zulqarnain Jalil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!