I have a service that makes GET requests to an API server and returns JSON in the form of a Promise. Below is the code for the service:
import { Injectable } from "@angular/core";
import { HttpClientModule } from "@angular/common/http";
import { HttpModule, Http } from "@angular/http";
import { Person } from "./person";
import "rxjs/add/observable/of";
import { Response } from "@angular/http/src/static_response";
@Injectable()
export class PersonService {
constructor(private http: Http) {}
public getPeople(): Promise<any> {
return this.http.get("http://localhost:62066/api/values").toPromise();
}
}
After importing this service, I attempted to display the data fetched from the Promise as an unordered list:
import { Component, OnInit } from "@angular/core";
import { Person } from "../person";
import { PersonService } from "../person.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 personService: PersonService) {}
ngOnInit() {
var people = this.personService.getPeople();
console.log(people);
}
}
Below is the log output for 'people':
ZoneAwarePromise {zone_symbol__state: null, __zone_symbol__value: Array(0)} __zone_symbol__state : true __zone_symbol__value : Response {_body: "[{"personID":1,"name":"John","surname":"Doe"},{"personID":2,"name":"Jane","surname":"Smith"}]", status: 200, ok: true, statusText: "OK", headers: Headers, …} __proto : Object
I tried using ngFor directive to loop through the objects but encountered issues with displaying them on the HTML page:
<ul><li *ngFor="let person of people">
{{person.ID}} {{person.name}}
</li>
</ul>
Is there a way to create an array from the Promise or store the Promise data in a list? Apologies for the messy log code formatting.