1
私はREST APIからデータを表示しようとしています。ただし、データがロードされる前にUIがレンダリングされます。だから次のエラーが表示されます:NativeScriptとAngular2 - オブジェクトをバインドする方法は?
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);
});
}
}
テンプレート:あなたはngIf
ディレクティブまたはとしても知られている安全なナビゲーション演算子(?
)を(使用することができます
<ActionBar [title]="foo.name"></ActionBar>
<GridLayout>
<Label [text]="foo.description"></Label>
</GridLayout>
補足として、コンポーネントのngOnInitメソッドのように、別のサブスクリプション内の監視可能なサブスクリプションを購読しないことをお勧めします。最初の.subscribeを.map(fooId => this.fooService.get(fooId))で置き換えることができます。この方法では、ngOnDestroyの登録を解除するサブスクリプションが1つしかなく、コールバック地獄のように見えなくなります –