2017-02-18 74 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 [] = [];