Search code examples
angulartypescriptngoninit

undefined value return on ongonit for function parameter


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;
    });
}

Solution

  • 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();
     });
    }