![](/img/trans.png)
[英]Uncaught ReferenceError: angular is not defined I am having trouble with a chrome extension
[英]Angular 2 / 4 toPromise works but I am having trouble with Observables
我想把头围在Observables上
这是.toPromise
当前对我.toPromise
request.ts
get(url): Promise<any>
{
// HARD CODED A URL I FOUND , NOT USING THE "url" param
return this.http.get("https://conduit.productionready.io/api/profiles/eric").map(response => {
return response.json() || {success: false, message: "No response from server"};
}).catch((error: Response | any) => {
return Observable.throw(error.json());
}).toPromise();
}
这样可行,
来自
event.service.ts
功能...
this.Request.get("/user").then(response => {
console.log("Got response:", response);
}).catch(error => {
console.log("Got error:", error);
}).then(response => {
console.log("Another response:", response);
}).catch(error => {
console.log("Got another error:", error);
});
相反,我想做的是可观察的
所以
我尝试“订阅”
订户
我不太了解如何使用“数据”和“订阅”等。
var url = "https://conduit.productionready.io/api/profiles/eric";
var blah;
this.getDataObservable(url).subscribe(
data => {
blah = data;
console.log("I CANT SEE DATA HERE: ", blah);
}
);
通话功能
getDataObservable(url: string) {
return this.http.get(url)
.map(data => {
data.json();
// the console.log(...) line prevents your code from working
// either remove it or add the line below (return ...)
console.log("I CAN SEE DATA HERE: ", data.json());
return data.json();
});
}
如何执行此操作的示例很多 ...这里是一个:
服务
getProducts(): Observable<IProduct[]> {
return this._http.get(this._productUrl)
.map((response: Response) => <IProduct[]> response.json())
.do(data => console.log('All: ' + JSON.stringify(data)))
.catch(this.handleError);
}
private handleError(error: Response) {
// in a real world app, we may send the server to some remote logging infrastructure
// instead of just logging it to the console
console.error(error);
return Observable.throw(error.json().error || 'Server error');
}
零件
ngOnInit(): void {
this._productService.getProducts()
.subscribe(products => this.products = products,
error => this.errorMessage = <any>error);
}
注意:这使用的是原始Http服务,而不是新的HttpClient服务。
要理解此代码,您需要了解Observables以及Http的工作方式。 我会强烈建议你阅读在Angular.io的文档,通过本教程在angular.io工作,或观看当然像这样的: https://app.pluralsight.com/library/courses/angular-2-getting-开始 (您可以注册一个免费的一周观看。)
您的服务应该是这样的,因此您可以订阅组件
getDataObservable(url: string) {
return this.http.get(url).map(data => data.json()).catch(error=>Observable.throw(error));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.