[英]Angular 7 Http response
在組件中時,我從 Rest Api 得到響應,但是當我將代碼移至服務時,它不會給出數據響應。
這是我的組件中的代碼:
import { HttpClient } from '@angular/common/http';
nodes: any = [];
this.http.get('https://prokom-aimcms-dev.azurewebsites.net/api/contentapi/getall', {observe: 'response'})
.subscribe(response => {
this.nodes = response;
});
這將給出響應:
{
"headers": {
"normalizedNames": {},
"lazyUpdate": null,
"lazyInit": null,
"headers": {}
},
"status": 200,
"statusText": "OK",
"url": "someUrl",
"ok": true,
"type": 4,
"body": [
{
"id": 1,
"contentId": "59f37a5c-b209-4813-a11b-0d2e34ec5530",
"created": "2019-02-05T08:49:00.207078",
"modified": "2019-02-21T13:02:19.2983893",
"title": "TEst",
"published": null,
"creator": null,
"state": 0,
"sortIndex": 0,
"contentObject": null,
"metaObject": null,
"parameterObject": null,
"version": 0,
"language": "nb_no",
"parentContent": "00000000-0000-0000-0000-000000000000",
"relatedContents": [
"aa8e9c90-adbb-4853-98b9-53e431e27c4b"
],
"tags": [],
"categories": []
},
.......
但是,如果我將其移至服務 (somename.service.ts):
import { HttpClient } from '@angular/common/http';
public getAllNodes(): Observable<any> {
return this.http.get('someURL', {observe: 'response'})
.map(response => {
return response;
});
}
並從組件調用它(somename.component.ts)
this.nodes = this.aimService.getAllNodes().subscribe();
那么響應將是:
{
"closed": true,
"_parent": null,
"_parents": null,
"_subscriptions": null,
"syncErrorValue": null,
"syncErrorThrown": false,
"syncErrorThrowable": true,
"isStopped": true,
"_parentSubscription": null,
"destination": {
"closed": true,
"_parent": null,
"_parents": null,
"_subscriptions": null,
"syncErrorValue": null,
"syncErrorThrown": false,
"syncErrorThrowable": false,
"isStopped": true,
"_parentSubscription": null,
"destination": {
"closed": true
},
"_parentSubscriber": null,
"_context": null
}
}
有誰知道為什么會這樣? 以及我如何從服務中獲取數據。
this.nodes = this.aimService.getAllNodes().subscribe();
你在這里所做的本質上是將訂閱的值分配給this.nodes
當您訂閱時,您將能夠提供“回調”,這是您需要做的,以便訪問您的數據。 如下:
this.aimService.getAllNodes().subscribe((data) =>
{
// you'll see the expected data here
), (error) =>
{
// if the request fails, this callback will be invoked
});
如果你是Observables
和 RXJS 領域的新手,我強烈建議你去這里
您應該訂閱並分配來自訂閱的值:
this.aimService.getAllNodes().subscribe((response) => {
this.node = response.data // or any value from the response object
}, (err) => {
console.log(error); // any error should be caught here
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.