Unable to read subscribe property undefined in nested calls in Angular 2

I want to subscribe to company-list.component to getCompanies() from company.service . However, I get the following error:

Unable to read subscribe property undefined

This is the code:

company.service.ts

  getCompaniesOfUser() { let r; this.userService.getUser().subscribe( res=> r = res, err => console.log(err), ()=>(this.getCompaniesWithSpecificLink()) ) } getCompaniesWithSpecificLink() { if (isAdmin == false) { url = '/user/companies'; } else { url = '/companies'; } return this.getCompanies(url); } getCompanies(url):Observable<Company[]> { return this.http.get(this.host + url) .map((res:Response) => res.json()); } 

company-list.component.ts

 companies:Company[]; public getTheCompanies() { this._companyService.getCompaniesOfUser() .subscribe(companies => this.companies = companies); <-- the error occurred here } 
+2
source share
1 answer

The Subscribe method should be used for the observable, but your getCompaniesOfUser() method does not return anything, therefore it is the void method.

If you want to call back to rest. As one input, depending on the output of others. You must use the flatMap operator.

Check this answer, for example: fooobar.com/questions/418044 / ...

Something like this should work:

 getCompaniesOfUser() { return this.userService.getUser().flatMap( (resp) => { return this.getCompaniesWithSpecificLink(); }); } 
+3
source

Source: https://habr.com/ru/post/1013468/


All Articles