我导入了'rxjs / add / operator / toPromise';
在我的Ts文件中,我有类似的东西:
onChange(categoryid) {
//console.log('testing')
this.productService.getProductsOncategory(categoryid).subscribe(data => {
if (data.success) {
console.log('Products obtained');
} else {
console.log('Not obtained!');
}
});
}
我收到错误:
属性'subscribe'在'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(数据=>'...
,如何更改代码段答案 0 :(得分:2)
subscribe方法用于'Observable',因此您只需返回一个Observable Object。 然后像这样做你想做的事情
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));
答案 1 :(得分:0)
只需映射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());
}