【发布时间】:2016-08-16 15:34:52
【问题描述】:
谁能帮我看看我的模板中是否有语法错误?它不会报错,但也不会将数据填充到模板中:
<div *ngIf="(hero | async)">
<h2>{{hero}}</h2>
<h2>{{hero.name}} details!</h2>
<div>
<label>_id: </label>{{hero._id}}</div>
<div>
<label>name: </label>
<input [(ngModel)]="hero.name" placeholder="name" />
</div>
<button (click)="goBack()">Back</button>
</div>
组件代码
export class HeroDetailComponent implements OnInit {
errorMessage: string;
//@Input()
hero: Observable<Hero>;
constructor(
private _heroService: HeroService,
private _routeParams: RouteParams) {
}
ngOnInit() {
let _id = +this._routeParams.get('_id');
this._heroService.loadHero(_id);
this.hero = this._heroService.hero$;
this.hero.subscribe(data =>
console.log(data)
)
}
console.log(data) 打印:
对象{_id:11,名称:“尼斯先生”}
这意味着数据被正确检索。
<div> 块也出现了,这意味着 *ngIf 将对象视为非空。
<h2>{{hero}}</h2> 显示[object Object]。
但是为什么{{hero.name}} 没有显示?
【问题讨论】:
-
你搞混了一些事情。
hero是一个输入属性,但是你在 ngOnInit() 中为其分配了一个值——这很奇怪。分配的值是一个 Observable,它没有name属性,这就解释了为什么{{hero.name}}不起作用。这个答案应该可以帮助你:stackoverflow.com/a/34561532/215945 -
我更新了帖子并删除了@input。但还是一样。异步管道应该将可观察对象变成英雄对象?