0
我從角2文件,讓ngOnInit方法是從服務器上獲取數據的地方瞭解到,這樣我做什麼,但有問題:錯誤的諾言unresolbed角2
組件
import { Component, OnInit } from '@angular/core';
import { Champion } from './champion'
import { ChampionService } from './champion.service';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'champion',
template:
`
<div *ngIf="champion">
<h1> {{ champion.name }} </h1>
this is champion descirption
</div>
`,
})
export class ChampionComponent implements OnInit {
champion : Champion;
constructor(private championService : ChampionService,
private activatedRoute : ActivatedRoute)
{
}
ngOnInit() {
this.activatedRoute.params
.forEach(params => {
let id = +params['id']
this.championService.getChampion(id)
.then(champion => this.champion = champion);
});
}
}
服務
import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import { Champion } from './champion'
@Injectable()
export class ChampionService {
private url : string = "https://jsonplaceholder.typicode.com/users";
constructor(private http : Http) {
}
getChampions() : Promise<Champion[]> {
return this.http.get(this.url)
.toPromise()
.then(response => response.json() as Champion[]);
}
getChampion(id : number) : Promise<Champion> {
return this.http.get("https://jsonplaceholder.typicode.com/users/" + id)
.toPromise()
.then(response => {
return response.json() as Champion
})
}
}
,如果我的div
與刪除從模板我得到一個未解決的諾言錯誤,這意味着該模板在諾言解決之前呈現,所以冠軍是不明確的。
但我發現它非常令人不安,因此需要從div
與*ngIf
中的服務器中獲取數據的每個組件。
我做錯了嗎?
感謝和抱歉,我的英語不好