Angular 2简单HTTP获取

Angular 2简单HTTP获取

问题描述:

我想学习角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. 该组件被初始化
  2. 时间轴的构造函数被调用
  3. 的上init方法被称为
  4. 的上init方法将HTTP请求发送......
  5. 的上初始化完成
  6. 视图被初始化,iproducts.id称为

一段时间后......

  1. HTTP请求完成并且订阅回叫被称为设置你iproducts
  2. 所以,当您的视图初始化并且您的模板运行iproducts仍为空,因为您的http请求尚未完成。我会在if if ngIf=“iproducts”中包装该模板的这一部分,或者给iproducts一个默认值,该属性在访问属性时不会导致错误。

    第二个问题是你有一个数组,你试图访问它的ID .....我想你想用一个ngFor=“let iprod of iproducts”迭代数组中的项然后说iprod.id

    你仍然需要或者检查,以确保iproducts不为空或给它的[]

开始=>
+0

默认值谢谢。它有助于设定一个默认值。当然:) –

+1

很高兴我能帮上忙! – raykrow