繁体   English   中英

Angular 7 Http 响应

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM