从返回的 http 请求类型 Promise<Response> 中创建一个对象数组

Making an array of objects from returned type of http request Promise<Response>

我有一项服务请求来自 API 服务器的 GET 请求和 returns json 我将其转换为 Promise ,这里是服务代码

import { Injectable } from "@angular/core";
import { HttpClientModule } from "@angular/common/http";
import { HttpModule, Http } from "@angular/http";
import { Osoba } from "./osoba";
import "rxjs/add/observable/of";
import { Response } from "@angular/http/src/static_response";

@Injectable()
export class OsobaService {
  constructor(private http: Http) {}
  public getOsobe(): Promise<any> {
    return this.http.get("http://localhost:62066/api/values").toPromise();
  }
}

然后我导入了该服务,以便将该承诺中的数据列出到无序列表中

import { Component, OnInit } from "@angular/core";
import { Osoba } from "../osoba";
import { OsobaService } from "../osoba.service";
import "rxjs/add/operator/toPromise";

@Component({
  selector: "app-table-view",
  templateUrl: "./table-view.component.html",
  styleUrls: ["./table-view.component.css"]
})
export class TableViewComponent implements OnInit {
  constructor(private osobaService: OsobaService) {}

  ngOnInit() {
    var osobe = this.osobaService.getOsobe();
    console.log(osobe);
  }
}

这是 osobe 的日志

ZoneAwarePromise {zone_symbol__state:空,__zone_symbol__value:数组(0)} __zone_symbol__state : 真的 __zone_symbol__value : 响应 {_body: "[{"osobaID":1,"ime":"Aleksa ","prezime":"Jevtic…","prezime":"Stevanovic" ,"jmbg":"2504996854112"}]", status: 200, ok: true, statusText: "OK", headers: Headers, …} __proto : 对象

我尝试使用 ngFor 列出对象,但在 html 页面

上没有得到任何响应
<ul><li *ngFor="let osoba of osobe">
{{osoba.ID}} {{osoba.ime}}
</li>
</ul>

我如何从 Promise 创建数组?或者至少将 Promise 中的数据存储到列表中? 抱歉,日志代码丑陋,我不确定如何格式化它。

试试这个:

return this.http.get("http://localhost:62066/api/values").map(res => res.json());

这很正常,您必须将 API 设置为 .json():

import "rxjs/add/observable/map"; //<-- add this import


@Injectable()
export class OsobaService {
  constructor(private http: Http) {}
  public getOsobe(): Promise<any> {
    return this.http.get("http://localhost:62066/api/values")
      .map(res => res.json()) //<-- here 
      .toPromise();
  }
}

此方法 return 响应正文。

也检查 .ts,你有一个局部变量。无法从 html:

访问
export class TableViewComponent implements OnInit {
  osobe: Promise<any> //<-- add

  constructor(private osobaService: OsobaService) {}

  ngOnInit() {
    this.osobe = this.osobaService.getOsobe(); //<-- update
  }
}

此外,我认为您的 html 代码是错误的 var osobe = this.osobaService.getOsobe();

因为,您分配了一个可观察对象,但在您的 html 中您没有将 osobe 用作可观察对象。

我也必须添加异步管道:

<ul>
   <li *ngFor="let osoba of osobe | async">{{osoba.osobaID}} {{osoba.ime}}</li>
</ul>

您必须在服务函数调用中添加 then 和 catch,例如:

   this.osobaService.getOsobe().then((response) => {console.log(response);}).catch((error) => {console.log(error); });