Angular 7 Http响应

问题描述 投票:0回答:2

在组件中我从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
  }
} 

谁知道为什么会这样?我如何从服务中获取数据。

angular typescript angular7 angular-httpclient
2个回答
2
投票
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的领域,我强烈推荐去here


2
投票

您应该订阅并分配值:

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
 });
© www.soinside.com 2019 - 2024. All rights reserved.