2017-08-20 10 views
0

ノードからサービスのonInitにオブジェクトの配列を取得し、コンポーネントに割り当てようとしています。私はサービス中のデータを見ることができますが、コンポーネント内の変数に代入しようとすると、以下のエラーが発生します。私は自分のコードも含めました。私が必要とするのは、サービスからその配列を取り出し、それをコンポーネント内のファイナリストに割り当てることだけです。プロパティ 'includes'が 'Subscription'タイプにはありません-angular2

ERROR in 

    C:/Users/girija/Documents/animapp/src/app/components/list.component.ts (28,5): Type 'Subscription' is not assignable to type 'any[]'. 
     Property 'includes' is missing in type 'Subscription'. 

私のコードは以下の通りです: app.service.ts:

public finallist=[] 
    getList(){ 
      return this.http.get('/api/list').subscribe(data=>{ 
      this.finallist=JSON.parse(data['_body']); 
      return this.finallist; 
     }) 
     } 

app.component.ts:

totallist=[]; 
    ngOnInit() { 
     this.totallist=this.someService.getList(); 

     } 

答えて

2

subscribe返信Subscriptionオブジェクトこれはあなたが探しているものではありません。

app.service.ts

getList(): Observable<any> { 
    return this.http.get('/api/list').map(data => data['_body']); 
} 

app.component.ts

totallist=[]; 

ngOnInit() { 
    this.someService.getList().subscribe(data => this.totallist = data); 
} 
私はまだここに同じエラーを取得し
1

あなたが応答を変換するmap演算子を使用する必要がありますjsonタイプに

getList(){ 
      return this.http.get('/api/list') 
      .map(response=> <Type>response.json()) ///////// 
      .subscribe(data=>{ 
      this.finallist=JSON.parse(data['_body']); 
      return this.finallist; 
     }) 
     } 

注:<Type>は、厳密な型指定のために使用されている

+0

このような何かを試してみてください| – Gayathri

0

下記の私の答えを参照してください。サーバー、サービス、および最終的にコンポーネントからデータを取得する方法について説明します。 Receiving Jason instead of html。私はmongodBを使用していますが、あなたのバックエンドは異なるかもしれません。お役に立てれば。

関連する問題