2016-10-23 12 views
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> 
+0

補足として、コンポーネントのngOnInitメソッドのように、別のサブスクリプション内の監視可能なサブスクリプションを購読しないことをお勧めします。最初の.subscribeを.map(fooId => this.fooService.get(fooId))で置き換えることができます。この方法では、ngOnDestroyの登録を解除するサブスクリプションが1つしかなく、コールバック地獄のように見えなくなります –

答えて

3

エルヴィスオペレータ)がテンプレートを「保護する」:

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を読んだだけでなく、template syntax page about safe nagivation operator (?)示唆しています。

関連する問題