[英]Angular 2 Property subscribe does not exist on type Promise <any>
I have imported 'rxjs/add/operator/toPromise'; 我已经导入了'rxjs / add / operator / toPromise';
In my Ts file i have something like: 在我的Ts文件中,我有类似以下内容:
onChange(categoryid) {
//console.log('testing')
this.productService.getProductsOncategory(categoryid).subscribe(data => {
if (data.success) {
console.log('Products obtained');
} else {
console.log('Not obtained!');
}
});
}
I get error: 我得到错误:
Property 'subscribe' does not exist on type 'Promise'.
类型“ Promise”上不存在属性“ subscribe”。
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);
} }
How to i change the snippet if i have to use ' then(data => '... 如果我必须使用'then(data =>'...
subscribe method is for 'Observable', so you can just return an Observable Object. subscription方法适用于“可观察”,因此您只需返回一个可观察对象。 then do what you want to do like this
然后做你想做的事
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));
just map the http request and return it. 只需映射http请求并返回即可。 no need to create a new 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
})
.map((res: Response) => res.json());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.