NativeScript 和 Angular2 - 如何绑定对象?
NativeScript & Angular2 - How to bind an object?
我正在尝试显示来自 REST API 的数据。但是, UI 在加载数据之前呈现。所以我收到以下错误:
Cannot read property 'name' of undefined
如何绑定对象?
组件:
@Component({
selector: 'foo-detail',
templateUrl: 'foo.component.html',
providers: [FooService],
})
export class FooDetailComponent implements OnInit {
public foo:Foo;
constructor(private fooService:FooService,
private route:ActivatedRoute) {
}
ngOnInit() {
this.route.params
.map(params => params['id'])
.subscribe(fooId => {
this.fooService
.get(+fooId)
.subscribe(res => this.foo = res);
});
}
}
服务:
@Injectable()
export class FooService {
constructor(private http: Http) {}
get(fooId) {
return this.http.get('http://api.foo.com/foos/' + fooId)
.map(res => res.json())
.map(foo => {
return new Foo(foo.id, foo.name, foo.description);
});
}
}
模板:
<ActionBar [title]="foo.name"></ActionBar>
<GridLayout>
<Label [text]="foo.description"></Label>
</GridLayout>
您可以使用 ngIf
指令或安全导航运算符 (?
)(也称为 Elvis 运算符)"protect" 您的模板:
ngIf
指令
<div *ngIf="foo">
<ActionBar [title]="foo.name"></ActionBar>
<GridLayout>
<Label [text]="foo.description"></Label>
</GridLayout>
</div>
猫王运算符
<ActionBar [title]="foo?.name"></ActionBar>
<GridLayout>
<Label [text]="foo?.description"></Label>
</GridLayout>
</div>
我建议阅读official Angular 2 page about ngIf
directive to understand how it works, as well as template syntax page about safe nagivation operator (?
)。
我正在尝试显示来自 REST API 的数据。但是, UI 在加载数据之前呈现。所以我收到以下错误:
Cannot read property 'name' of undefined
如何绑定对象?
组件:
@Component({
selector: 'foo-detail',
templateUrl: 'foo.component.html',
providers: [FooService],
})
export class FooDetailComponent implements OnInit {
public foo:Foo;
constructor(private fooService:FooService,
private route:ActivatedRoute) {
}
ngOnInit() {
this.route.params
.map(params => params['id'])
.subscribe(fooId => {
this.fooService
.get(+fooId)
.subscribe(res => this.foo = res);
});
}
}
服务:
@Injectable()
export class FooService {
constructor(private http: Http) {}
get(fooId) {
return this.http.get('http://api.foo.com/foos/' + fooId)
.map(res => res.json())
.map(foo => {
return new Foo(foo.id, foo.name, foo.description);
});
}
}
模板:
<ActionBar [title]="foo.name"></ActionBar>
<GridLayout>
<Label [text]="foo.description"></Label>
</GridLayout>
您可以使用 ngIf
指令或安全导航运算符 (?
)(也称为 Elvis 运算符)"protect" 您的模板:
ngIf
指令
<div *ngIf="foo">
<ActionBar [title]="foo.name"></ActionBar>
<GridLayout>
<Label [text]="foo.description"></Label>
</GridLayout>
</div>
猫王运算符
<ActionBar [title]="foo?.name"></ActionBar>
<GridLayout>
<Label [text]="foo?.description"></Label>
</GridLayout>
</div>
我建议阅读official Angular 2 page about ngIf
directive to understand how it works, as well as template syntax page about safe nagivation operator (?
)。