2017-03-10 110 views
1

我在我的Angular2應用程序中有對象數組。當新對象到達時,我使用SignalR來填充數組。現在的問題是,當新的對象來到我的錯誤Observable <Array> Angular2

cannot read property of undefined

我騎着,由於其工作的異步和HTML我常帶內對象的對象可能是錯誤。

所以,現在的代碼如下所示:

<div *ngFor="let event of events"> 
     <div class="card overview"> 
      <div class="overview-content clearfix "> 
       <span class="overview-title" pTooltip="{{event.name}}">{{(event | async)?.user?.name}}/{{(event | async)?.date | date:"HH:mm" }}</span> 
       <span class="overview-badge "> <i class="material-icons ">{{getActivityIcon(event.activityId)}}</i> 
      <button type="button" pButton (click)="selectEvent($event,event,op);" icon="fa-search"></button> 
      </span> 

      </div> 
     </div> 
    </div> 

而現在的錯誤是

NgFor only supports binding to Iterables such as Arrays.

我的對象數組是在組件和看看下面:

events: Observable<Event[]>; 

我明白錯誤,但我怎樣才能使它現在工作?

+2

添加'| | async'在你的結尾* ngFor – shammelburg

+0

TypeError:無法讀取未定義的屬性'subscribe' – miechooy

+0

您可以訂閱組件中的observable並設置events屬性中的數據。 – shammelburg

回答

0

我認爲這就是你要找的。

The AsyncPipe accepts a Promise or Observable as input and subscribes to the input automatically, eventually returning the emitted values.

Angular.io - AsyncPipe

6

看來你是不知道什麼是async管和subscribe之間的區別,因爲你是用你的模板代碼一個奇怪的組合。使用異步管道或「手動」訂閱。 Async pipe將爲您訂購,不應與subscribe一起使用。

短簡單的例子,異步管道的第一種用法:

服務:

getEvents(): Observable<Event[]> { 
    return this.http.get('url') 
    .map(res => res.json()) 
} 

在組件,我們分配可觀察到我們觀察到的events

events: Observable<Event[]>; 

ngOnInit() { 
    this.events = this.myService.getEvents(); 
} 

在HTML中,我們使用async管道訂購我們:

<div *ngFor="let event of events | async"> 
    {{event.name}} 
</div> 

... Aaaand然後subscribe用法:

服務方法將是相同的,不同的是在組件:

events: Event[] = []; 

ngOnInit() { 
    this.myService.getEvents() 
    .subscribe(data => { 
     this.events = data; 
    }); 
} 

HTML:

在這裏,我認爲你混合async管與異步檢索的數據。因此,async管道不用於異步檢索的數據,而是用於訂閱Observable。

這給我們帶來了異步數據,所以如果你使用subscribe,你應該初始化數組,可能需要使用safe navigation operator或者如果你想,*ngIf,在你的模板不渲染部分除非在events中有數據。但我更喜歡安全的導航操作;)

希望這個幫助,並作出一些澄清:)

相關問題