Home > Mobile >  I can't get the value of a variable declared from another function in angular
I can't get the value of a variable declared from another function in angular

Time:06-05

I am trying to access the value of the variable existResults declared in a function before the one I am trying to call that variable, but I get an undefined value

  public existResults: any;

  ngOnInit(): void {
    this._activatedRoute.params.subscribe(params => {
      this.patientId = params['patient'];
      const testId = params['test'];
      this.getTestResults();
      this.getProccessesByTest(testId);
    });
  }

  getTestResults(id:any) {
    this._testsService.getTestResults(this.token, id, this.patientId).subscribe(
      response => {
        this.results = response.data;
        if (this.results.length == 0) {
          this.existResults = false;
        }else if(this.results.length > 0) {
          this.existResults = true;
        }
        console.log(this.existResults); //output true
      },
      error => {
        console.log(error);
      }
    );
  }

  getProccessesByTest() {
    console.log(this.existResults); //output undefined
  }

CodePudding user response:

Try this..
ngOnInit(): void {
this._activatedRoute.params.subscribe(params => {
    this.patientId = params['patient'];
    const testId = params['test'];
    this.getTestResults();
});
}

getTestResults(id: any) {
this._testsService.getTestResults(this.token, id,
    this.patientId).subscribe(
        response => {
            this.results = response.data;
            if (this.results.length == 0) {
                this.existResults = false;
            } else if (this.results.length > 0) {
                this.existResults = true;
            }

            this.getProccessesByTest();
            console.log(this.existResults); //output true
        },
        error => {
            console.log(error);
        }
    );
    }

CodePudding user response:

  1. You are passing an argument to the wrong method.
  2. Don't forget that you are working with asynchronous code.

Try this:

public patientId: any;
public existResults: any;

 ngOnInit(): void {
   this._activatedRoute.params
     .pipe(
       tap(({patient}) => this.patientId = patient),
       switchMap(({test}) => this.getTestResults(test))
     )
     .subscribe(_ => this.getProccessesByTest());
 }

 getTestResults(id:any): Observable<any> {
   return this._testsService.getTestResults(this.token, id, this.patientId)
     .pipe(
       tap(response => {
         this.results = response.data;
         this.existResults = !(this.results.length == 0);
       }),
       tap(_ => console.log(this.existResults)),
       catchError(console.log)
     );
 }
  • Related