2017-09-22 54 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