【发布时间】:2016-09-24 21:27:47
【问题描述】:
我从 Angular 2 文档中了解到 ngOnInit 方法是从服务器获取数据的地方,所以我做什么但有问题:
组件
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 和*ngIf,我会得到一个未解决的promise 错误,这意味着模板是在promise 解决之前呈现的,所以冠军是未定义的。
但我发现将需要从服务器获取数据的每个组件都包装在 div 和 *ngIf 中非常令人不安。
我做错了吗??
感谢和抱歉我的英语不好
【问题讨论】:
标签: angular typescript