2017-09-22 51 views
0

我非常新的角度2,我試圖做到的是簡單的:角2調用API

  1. 通過路由
  2. 調用API與類別ID
  3. 獲取傳遞的類ID
  4. 填充變量「類別」的數據與來自API返回和顯示分類名

我的觀點是簡單:

<h3>{{category.name}}</h3> 

組件代碼:

import { Component, Inject } from '@angular/core'; 
import { Http } from '@angular/http'; 
import { ActivatedRoute } from '@angular/router'; 
@Component({ 
    selector: 'browse-category', 
    template: require('./browse-category.component.html'), 
    styles: [require('./browse-category.component.css')] 
}) 
export class BrowseCategoryComponent { 
    products: IProduct[]; 
    category: ICategory; 
    categoryId: number; 
    constructor(private route: ActivatedRoute, private http: Http, @Inject('ORIGIN_URL') private originUrl: string) { 

    } 

    ngOnInit(): void { 
     this.route.params.subscribe(params => { 
      this.categoryId = +params['categoryId']; 
      // get category details 
      this.http.get(this.originUrl + '/api/Category/' + this.categoryId).subscribe(result => { 
       var data = result.json().data; 
       if (data != null && result.status === 200) { 
        this.category = data; 
        console.log(this.category); 
       } 
      }); 
     }); 
    } 
} 

如果我禁用了該視圖的輸出,我能夠看到的console.log輸出,如果我不這麼做,我得到以下錯誤:

NodeInvocationException:未捕獲(承諾):TypeError:無法讀取未定義的屬性「名稱」 TypeError:無法讀取未定義的屬性「名稱」

我認爲這是因爲承諾尚未返回。理想情況下,解決這個問題的最佳方法是什麼?

+0

什麼是console.log輸出? – jhenderson2099

回答

1

使用{{category?.name}} 這稱爲「安全導航」操作符,如果它被定義並且不爲null,它將只嘗試訪問類別。

+0

貓王操作符實際上是「?:」。這是[「安全導航」操作符](https://angular.io/guide/template-syntax#expression-operators)。 – jhenderson2099

+0

對,謝謝,修正。 – ronenmiller