2017-06-12 56 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離開工作,請評論,如果你能解決這種類型的不匹配錯誤,否則將明天看。 –