在组件中,我从Rest获得响应,但当我将代码移到服务中时,它将不会给出数据响应。
这是我组件中的代码:
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
}
} 有人知道为什么会这样吗?以及如何从服务中获取数据。
发布于 2019-02-25 15:03:35
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领域还不熟悉,我强烈建议您使用这里
发布于 2019-02-25 15:04:29
您应该订阅并分配来自订阅的值:
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
});https://stackoverflow.com/questions/54868891
复制相似问题