2017-07-20 23 views
0

'rxjs/add/operator/toPromise'をインポートしました。私のTSファイルで 角2プロパティサブスクリプションがタイプPromiseに存在しません<any>

は、私のようなものを持っている:

onChange(categoryid) { 
//console.log('testing') 
this.productService.getProductsOncategory(categoryid).subscribe(data => { 
    if (data.success) { 

    console.log('Products obtained'); 
    } else { 
    console.log('Not obtained!'); 
    } 
}); 
} 

私が取得エラー:

Property 'subscribe' does not exist on type 'Promise'.

getProductsOncategory(category_id) { 

let catUrl = "API URL" 
let headers = new Headers(); 
headers.append('Content-Type', 'application/json'); 
let catIdObj = JSON.stringify({ category_id: category_id }) 
return this.http.post(catUrl, catIdObj, { headers: headers }) 
    .toPromise() 
    .then((response: Response) => response.json().data) 
    //.map((response: Response) => response.json()) 
    //.do(data => console.log(JSON.stringify(data))) 
    .catch(this.handleError); 

}私が使用している場合

がどのように私はスニペットを変更するには'then(data =>' ...

答えて

0

ju httpリクエストをマップして返します。新しい約束を作成する必要はありません。

getProductsOncategory(category_id) { 

    let catUrl = "API URL" 
    let headers = new Headers(); 
    headers.append('Content-Type', 'application/json'); 
    let catIdObj = JSON.stringify({ 
     category_id: category_id 
    }) 

    return this.http.post(catUrl, catIdObj, { 
      headers: headers 
     }) 
     .map((res: Response) => res.json()); 
} 
2

subscribeメソッドは「Observable」のため、Observableオブジェクトを返すことができます。 このようにしたい操作を実行します

getProductsOncategory(category_id): Observable<Response>{ 

     let catUrl = "API URL" 
     let headers = new Headers(); 
     headers.append('Content-Type', 'application/json'); 
     let catIdObj = JSON.stringify({ category_id: category_id }) 
     return this.http.post(catUrl, catIdObj, { headers: headers }) 
    } 

this.productService.getProductsOncategory(categoryid) 
    .map(response => response.json().data) 
    .subscribe(data => doSomething(data),err => catchErr(err)); 
関連する問題