2017-11-25 239 views
0

我想學習角2,我無法得到最簡單的http上班。Angular 2簡單HTTP獲取

我得到的運行時錯誤

Cannot read property 'id' of undefined 

但在同一時間被其迷惑了我很多的頁面上顯示「身份證」的價值。它怎麼可能是未定義的並且仍然顯示。

我從的WebAPI返回此JSON

{ 
"category":["some string"], 
"icon_url":"some string", 
"id":"some string", 
"url":"some string", 
"value":"some string" 
} 

我已經創建了一個接口

export interface IProduct { 
category: string; 
icon_url: string; 
id: string; 
url: string; 
value: string; 
} 

在我的服務,我有這個方法調用的WebAPI,並返回JSON

getproducts(context: ContentAndStructureContext): Observable<IProduct[]> { 
return this.http.get(routes.url(context), { cache: true }) 
    .map((res: Response) => <IProduct[]>res.json()) 
    .do(data => console.log(data)); 

}

工作正常,數據對象正在記錄到控制檯。到目前爲止好

在我的組件我有打電話的getProducts方法

export class HomeComponent implements OnInit { 
isProductLoading: boolean; 
iproducts: IProduct[]; 

constructor(private contentAndStructureService: ContentAndStructureService) {} 

ngOnInit() { 
this.isLoading = true; 
this.isProductLoading = true;  

    this.contentAndStructureService.getproducts({ category: 'dev' }) 
    .pipe(finalize(() => { this.isProductLoading = false; })) 
    .subscribe(iproducts => this.iproducts = iproducts); 
} 
} 

這是我的HTML。它打印iproducts.id的值就好了。

<div class="container"> 
    <mat-card>  
    <mat-card-content>  
     <mat-card-subtitle> 
     <app-loader [isLoading]="isProductLoading" size="1.5"></app-loader> 
     <q [hidden]="isProductLoading">{{iproducts.id}}</q> 
     </mat-card-subtitle> 
    </mat-card-content> 
    </mat-card> 
</div> 

但在控制檯中的跟隨誤差得到記錄

ERROR TypeError: Cannot read property 'id' of undefined 
at Object.eval [as updateRenderer] (home.component.html:13) 
at Object.debugUpdateRenderer [as updateRenderer] (core.js:14377) 
at checkAndUpdateView (core.js:13513) 
at callViewAction (core.js:13858) 
at execComponentViewsAction (core.js:13790) 
at checkAndUpdateView (core.js:13514) 
at callViewAction (core.js:13858) 
at execEmbeddedViewsAction (core.js:13816) 
at checkAndUpdateView (core.js:13509) 
at callViewAction (core.js:13858) 

我不明白的ID如何能不確定,並在同一時間的價值得到印刷就好了......我不知道如何解決它。我花了數不清的時間,希望有人有時間讓我看看我在這裏做錯了什麼。

回答

1

我認爲你有兩個問題。首先是異步。赫雷什的發生了什麼

  1. 該組件被初始化
  2. 時間軸的構造函數被調用
  3. 的上init方法被稱爲
  4. 的上init方法將HTTP請求發送......
  5. 的上初始化完成
  6. 視圖被初始化,iproducts.id稱爲

一段時間後......

  • HTTP請求完成並且訂閱回叫被稱爲設置你iproducts
  • 所以,當您的視圖初始化並且您的模板運行iproducts仍爲空,因爲您的http請求尚未完成。我會在if if ngIf=「iproducts」中包裝該模板的這一部分,或者給iproducts一個默認值,該屬性在訪問屬性時不會導致錯誤。

    第二個問題是你有一個數組,你試圖訪問它的ID .....我想你想用一個ngFor=「let iprod of iproducts」迭代數組中的項然後說iprod.id

    你仍然需要或者檢查,以確保iproducts不爲空或給它的[]

    +0

    默認值謝謝。它有助於設定一個默認值。當然:) –

    +1

    很高興我能幫上忙! – raykrow