Cannot read property 'subscribe' of undefi

2019-05-18 21:25发布

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

Cannot read property 'subscribe' of 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
}

1条回答
Rolldiameter
2楼-- · 2019-05-18 21:47

Subscribe method must be used on an observable but your getCompaniesOfUser() method is not returning anything thus is a void method.

If you want to call back-to-back rest services. Like one's input depending on the others' output. You should use the flatMap operator.

Check this answer for example: https://stackoverflow.com/a/36712707/5706293

Something like this should work:

getCompaniesOfUser() {
    return this.userService.getUser().flatMap( (resp) => {
        return this.getCompaniesWithSpecificLink();
        });
}
查看更多
登录 后发表回答