![](/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.