无法读取Angular 2中的嵌套调用中未定义的属性"subscribe" [英] Cannot read property 'subscribe' of undefined in nested calls in Angular 2

查看:91
本文介绍了无法读取Angular 2中的嵌套调用中未定义的属性"subscribe"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从company.service订阅getCompanies()上的company-list.component.但是我收到以下错误:

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

无法读取未定义的属性"subscribe"

Cannot read property 'subscribe' of undefined

这是代码:

  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
}

推荐答案

必须在可观察的对象上使用订阅方法,但是您的getCompaniesOfUser()方法不返回任何内容,因此是无效方法.

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

如果您要拨打背靠背休息服务.就像一个人的输入取决于其他人的输出.您应该使用flatMap运算符.

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.

例如,查看以下答案: https://stackoverflow.com/a/36712707/5706293

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

这篇关于无法读取Angular 2中的嵌套调用中未定义的属性"subscribe"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆