我有以下的打字稿服務(app.component.ts):角4個顯示元素
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);
}
}
這是我app.component.html(只是從它的一個片段):
現在<div class="ui grid posts">
<app-powerplant
*ngFor="let powerPlant of powerPlants"
[powerPlant]="powerPlant">
</app-powerplant>
</div>
,在我powerplant.component.html,我有這樣的:
進口{組件,輸入的OnInit}從 '@角/核心'; 從'../shared/models/powerplant.model'導入{PowerPlant};
@Component({
selector: 'app-powerplant',
templateUrl: './powerplant.component.html',
styleUrls: ['./powerplant.component.css']
})
export class PowerplantComponent implements OnInit {
@Input() powerPlant: PowerPlant;
constructor() { }
ngOnInit() {
}
}
最後,是應該顯示動力項目的一個是這樣的:
<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>
我可以看到服務器發送我的陣列上得到下面的控制檯日誌方法顯示:
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();
});
}
哪裏的console.log打印我就行了,按照如在截圖中看到:
那麼爲什麼toPromise()失敗?只是爲了信息,這是我的動力模型看起來像:
export interface PowerPlant {
powerPlantId: number;
powerPlantName: string;
minPower: number;
maxPower: number;
powerPlantType: string;
rampRateInSeconds?: number;
rampPowerRate?: number;
}
並沒有多大的差別!這就是我得到 - 我的結果=>未定義 – sparkr
更新的答案,這可能是它。 –
是的!就是這樣!涼!感謝您的建議! – sparkr