/ / Affichage angulaire de 4 éléments d’une promesse - json, angular, http, dactylographie, observable

Angular 4 Display Elements d'une promesse - json, angulaire, http, dactylographié, observable

J'ai le service de typographie suivant (app.component.ts):

import { Component, OnInit } from "@angular/core";
import { ApiService } from "./shared/api.service";
import {PowerPlant} from "./shared/models/powerplant.model";
import "rxjs/add/operator/toPromise";

@Component({
selector: "app-root",
providers: [ApiService],
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
// represents the URL"s
allPowerPlantsURL = "powerPlants";
// represents the data
powerPlants: PowerPlant[];

ngOnInit(): void {
this.allPowerPlants();
}

constructor(private apiService: ApiService) {
}

allPowerPlants(onlyActive: boolean = false, page: number = 1): void {
const params: string = [
`onlyActive=${onlyActive}`,
`page=${page}`
].join("&");
const path = `${this.allPowerPlantsURL}?${params}`;
this.apiService.get(path)
.toPromise()
.then(elem => {
console.log("In the allPowerPlants");
console.log(elem); **// prints undefined here**
this.powerPlants = <PowerPlant[]> elem; }
)
.catch(this.handleError);
}

private handleError(error: any): Promise<any> {
console.error("An error occurred", error);
return Promise.reject(error.message || error);
}
}

Ceci est mon app.component.html (juste un extrait de celui-ci):

<div class="ui grid posts">
<app-powerplant
*ngFor="let powerPlant of powerPlants"
[powerPlant]="powerPlant">
</app-powerplant>
</div>

Maintenant, dans mon powerplant.component.html, j'ai ceci:

importer {Component, Input, OnInit} depuis "@ angular / core"; importer {PowerPlant} de "../shared/models/powerplant.model";

@Component({
selector: "app-powerplant",
templateUrl: "./powerplant.component.html",
styleUrls: ["./powerplant.component.css"]
})
export class PowerplantComponent implements OnInit {

@Input() powerPlant: PowerPlant;

constructor() { }

ngOnInit() {
}
}

Et enfin, celui qui est censé afficher les éléments PowerPlant est le suivant:

<div class="four wide column center aligned votes">
<div class="ui statistic">
<div class="value">
{{ powerPlant.powerPlantId }}
</div>
<div class="label">
Points
</div>
</div>
</div>
<div class="twelve wide column">
<div class="value">
MaxPower: {{ powerPlant.maxPower }} MinPower: {{ powerPlant.minPower }}
</div>
<div class="value">
MaxPower: {{ powerPlant.maxPower }} MinPower: {{ powerPlant.minPower }}
</div>
<div class="value">
PowerPlantType: {{ powerPlant.powerPlantType }} Organization: {{ powerPlant.powerPlantName }}
</div>
</div>

Je peux voir que le serveur m'envoie le tableau comme le montre le journal de console suivant sur la méthode get:

  get(path: string, params: URLSearchParams = new URLSearchParams()): Observable<any> {
console.log("sending request to " + `${environment.api_url}${path}`);
return this.http.get(`${environment.api_url}${path}`, { search: params })
.catch(this.formatErrors)
.map((res: Response) => {
console.log(res.json());
res.json();
});
}

Où la ligne console.log m'imprime ce qui suit, comme le montre la capture d'écran:

entrer la description de l'image ici

Alors pourquoi la toPromise () échoue? Juste pour information, voici à quoi ressemble mon modèle PowerPlant:

export interface PowerPlant {
powerPlantId: number;
powerPlantName: string;
minPower: number;
maxPower: number;
powerPlantType: string;
rampRateInSeconds?: number;
rampPowerRate?: number;
}

Réponses:

1 pour la réponse № 1

Y a-t-il une raison spécifique d'utiliser le toPromise() méthode ? Est-ce que cela fonctionne lors d'une inscription normale?

Essayez de changer cela

this.apiService.get(path)
.toPromise()
.then(elem => {
console.log("In the allPowerPlants");
console.log(elem); **// prints undefined here**
this.powerPlants = <PowerPlant[]> elem; }
)

pour ça :

this.apiService.get(path).subscribe(result => {
console.log("Im the result => ", result);
this.powerPlants = <PowerPlant[]> result;
});

C’est peut-être parce que vous ne renvoyez pas le résultat analysé dans votre .map() méthode et vous ne pouvez donc pas obtenir la réponse dans votre promesse / abonnement.

.map((res: Response) => res.json()); // return is inferred in this syntax


.map((res: Response) => {
return res.json(); // here it"s not
});

0 pour la réponse № 2

Il est lié à vous votre ApiService, vous avez oublié de revenir res.json dans ton .map

  get(path: string, params: URLSearchParams = new URLSearchParams()): Observable<any> {
console.log("sending request to " + `${environment.api_url}${path}`);
return this.http.get(`${environment.api_url}${path}`, { search: params })
.catch(this.formatErrors)
.map((res: Response) => {
console.log(res.json());
return res.json();
});
}