0

have two functions which , first function returns the result which stored in a variable, the same returned result variable passed as parameter in second function to hit the service. as explained code below , the two functions are invoked on ongonit , as a sequence the second function not able to catch the result of variable returned from function.Is there a way to over come this?

TS code:

udata:string;

ngOninit(){
    this.f1();
    this.f2();
}

f1(){
    this.service.getudata().subscribe(res => {
        this.udata = res;
    });
}

f2(){
    this.service.getudatas(this.udata).subscribe(res => {
        const data = res;
    });
}
Ghoul Ahmed
  • 4,446
  • 1
  • 14
  • 23
vijay munnangi
  • 43
  • 1
  • 4
  • 13

2 Answers2

1

you can use RXJS chaining solution with flatMap like this:

ngOninit(){
    this.f1().pipe(
    flatMap( x => this.f2(x)))
    .subscribe(res => const data = res);
}

f1(){
    return this.service.getudata();
}

f2(udata){
   return this.service.getudatas(udata);
}
Ghoul Ahmed
  • 4,446
  • 1
  • 14
  • 23
0

f2() is being called before your subscription in f1() returns, to solve this you could call this.f2() from within your subscription response.

f1(){
 this.service.getudata().subscribe(res =>{
  this.udata = res;
  this.f2();
 });
}
Dylan Anlezark
  • 1,256
  • 2
  • 12
  • 27