3

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
}
Claudiu Matei
  • 4,091
  • 3
  • 19
  • 33
  • You need to create a custom promise/observable to return it from getCompaniesOfUser, refer [this answer](http://stackoverflow.com/a/36383337/2435473) would help you. – Pankaj Parkar May 20 '16 at 08:28

1 Answers1

4

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();
        });
}
Community
  • 1
  • 1
eko
  • 39,722
  • 10
  • 72
  • 98