2017-06-12 54 views
0

撷取结果的阵列这是我的服务代码来获取结果的数组:无法从angular2服务

getIndustries(): Observable<any> { 
    return this.http.get(`${IndustriesService.BASE_URI}/?searchTerm=`) 
        .map((res: Response) => res.json()) 
        .catch((err: any) => Observable.throw('Server Error')); 
    } 

下面是我的部件的构造和与上述定义的服务进行通信的方法。

protected searchData: Array<Industry>; 
    constructor(private completerService: CompleterService, 
       private route: ActivatedRoute, 
       private industriesService: IndustriesService) { 
     this.fetchIndustryCodes(); 
    } 

    private fetchIndustryCodes(): Subscription { 
    return this.route.params 
     .switchMap((industries: Industry[]) => this.industriesService.getIndustries()) 
     .subscribe((industries_data: Industry[]) => { 
     this.searchData = industries_data 
     }); 
    } 

当我试图把它打印出来searchData在构造它打印认购对象。我不知道如何通过上述订阅获取数据。

任何方向对此将是一个很大的帮助!

+0

看起来你应该把你的搜索词作为url参数发送出去,但你永远不会填充它“?searchTerm =”...你需要把你的搜索词变量放在那里。 – ganders

+0

另外,您是否计划吞咽从您的服务呼叫返回的任何错误? – ganders

回答

1

据我所知,你想在你的构造函数中使用searchData,但是你无法调用异步调用需要时间,并且在fetchIndustryCodes()完成之前构造函数中的代码才会执行​​。如果是这样的话,那你为什么不在subscribe并且在构造函数本身中等待呢?

constructor(private completerService: CompleterService, 
      private route: ActivatedRoute, 
      private industriesService: IndustriesService) { 

      this.fetchIndustryCodes().subscribe(
      (industries_data) => { 
       this.searchData = industries_data; 
       // whatever you want to do here. 
      }, (err) => {console.log("error here")}); 
} 


private fetchIndustryCodes(): Observable<type> { 
    return this._activatedRoute.params 
     .switchMap((industries) => this.industriesService.getIndustries()) 
     .catch((err) => {console.log(err); return "service error";}) 
} 
+0

试过以上的解决方案,我想我差不多在那里。它在this.searchData = industry_data给出错误;错误是:[ts] 输入'string | Observable '不可分配为键入'Industry []'。 注意:我已经声明searchData为受保护的searchData:Array ; – Ajay

+0

试着用的'fetchIndustryCodes返回类型()''如可观察<阵列>'寻找到为什么orred'可观察'导致问题订阅 –

+0

虽然'可观察<阵列> |任何“工作正常,很明显:P离开工作,请评论,如果你能解决这种类型的不匹配错误,否则将明天看。 –