2017-02-18 70 views
1

我已经把一张支票在我的HTML属性上不能在* ngIf设置条件angular2 directiive

<div class="row" *ngIf="!products.length"> 
    <div class="col-12">No Records Found</div> 
</div> 
<div class="row" *ngIf="products.length"> 
    <div class="col-12"> 
     <table class="table"> 
      <thead> 
      <tr> 
       <th>name</th> 
       <th>description</th> 
       <th>category</th> 
       <th>price</th> 
       <th>quantity</th> 
      </tr> 
      </thead> 
      <tbody> 
      <tr *ngFor="let product of products"> 
       <th scope="row">1</th> 
       <td>Mark</td> 
       <td>Otto</td> 
       <td>@mdo</td> 
      </tr> 
      </tbody> 
     </table> 
    </div> 
</div> 

的长度和我取出由一个服务的数据。这里是我的组件

export class ManageComponent implements OnInit { 
    products: any[]; 

    constructor(private sharedservice: SharedService) { 
    } 

    ngOnInit() { 
     this.loadData(); 
    } 

    loadData() { 
     this.sharedservice.getData() 
      .subscribe(
       products => { 
        console.log('p: ', products); 
        this.products = products 
       } 
      ) 
    } 
} 

所以当数据库中没有数据时,它只是返回空数组。

但angular2是显示错误:在这个

TypeError: Cannot read property 'length' of undefined 

什么想法?

回答

3

products不是由您的异步操作(sharedservice.getData())分配的时间定义的。你可以做的是重写你的ngIfs。所以他们会先检查是否定义了product

实施例:

*ngIf="products && products.length" 
3

可以使用安全操作,以及:

<div class="row" *ngIf="products?.length"> 
+0

是的,我用过这个。这个安全操作员的含义是什么? –

2

需要声明的产品作为阵列型;

这样 -

products:any [] = [];