我无法获取从 angular 中的另一个函数声明的变量的值

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

我试图访问函数中声明的变量 existResults 的值,然后我试图调用该变量,但我得到一个未定义的值

  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
  }
  1. 您将参数传递给了错误的方法。
  2. 不要忘记您正在使用异步代码。

试试这个:

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

试试这个..

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

将 getProccessesByTest() 调用到函数 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;
        }
        console.log(this.existResults); //output true
this.getProccessesByTest(testId);
      },
      error => {
        console.log(error);
      }
    );
  }