2017-04-17 152 views
1

過濾一個數組列表,我使用的觀測在我的角度應用程序,它工作正常。但是,我遇到了一個有點混亂的情況。在一個組件,我成功訂閱可觀察到的,然後過濾結果,就像這樣:使用觀測量和角度應用

this.clientsService.getAll() 
    .subscribe(resRecordsData => { 
     this.records = resRecordsData; 
     this.inactiveRecords = this.records.filter(record => record.category && record.category.includes('inactive')); 
     this.records = this.inactiveRecords; 
    }, 
    responseRecordsError => this.errorMsg = responseRecordsError); 

然而,在另一組件,而我做幾乎同樣的事情,我正在印刷的錯誤控制檯,上面寫着:

例外:_this.records.filter不是一個函數

這是組件的樣子:

optionReceived(option) { 
    console.log('Consulting: ' + option.toolbarLabel); 
    if (option.toolbarLabel === 'OT') { 
     console.log('Consulting: OT Filter Activated!'); 
     this.clientService.getByCategory('consulting', 1, this.pagesize) 
     .subscribe(resRecordsData => { 
      this.records = resRecordsData; 
      this.OTRecords = this.records.filter(record => record.type && record.type.includes('OT')); 
      this.records = this.OTRecords; 
     }, 
     responseRecordsError => this.errorMsg = responseRecordsError); 
    } else { 
     return this.records; 
} 

是什麼在第二種情況下的問題?爲什麼我在那裏得到錯誤,而不是在第一種情況下?

+0

如果您在各種情況下懸停在this.records,你看到的數據類型?這兩個例子有什麼不同? – DeborahK

+0

它們看起來是相同的:(屬性)ConsultingComponent.records:任何[] – Muirik

+0

「記錄」被設置爲在兩個成分的空數組。 – Muirik

回答

2

爲什麼不能過濾您訂閱

this.clientsService.getAll() 
    .filter(record => record.category && record.category.includes('inactive')) 
    .subscribe(
     resRecordsData => { 
      this.records = resRecordsData; 
     }, 
     err => this.errorMsg = err 
    ); 

之前第一種情況下,我相信角使用RxJS,採取參考從http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-filter

+0

無論哪種方式 - 問題是,爲什麼第二個示例在第一個示例不會返回錯誤?在這兩種情況下,我都是在訂閱後進行篩選。所以那不是問題。 – Muirik

+0

如果結果是單個項目,過濾器將適用於數組。你確定你在那裏收藏嗎?可以放一個console.log – Ovais

+0

非常有趣。令我驚訝的是,這工作!非常感激! – Muirik

0

這是因爲異步特性,您可以使用skipWhile運營商

this.clientService.getByCategory('consulting', 1, this.pagesize) 
    .skipWhile(data => { 
     if(data.length) { 
      return false; 
     } 
    }) 
    .subscribe(resRecordsData => { 
     this.records = resRecordsData; 
     this.OTRecords = this.records.filter(record => record.type && record.type.includes('OT')); 

    }, 
    ((responseRecordsError) => {this.errorMsg = responseRecordsError}); 

注:確保this.records=[];被實例化

更新: 你不應該分配this.records=this.OTRecords;認購裏面,因爲你得到了未定義的錯誤。

在過濾元件可能包含多個對象(陣列),而不是在第二種情況下

+0

仍然收到相同的錯誤。另外,如果異步是問題,那麼兩者肯定會是個問題。我的觀點是,第二個例子返回一個錯誤,第一個例子沒有。 – Muirik

+0

看看我更新的答案 – Aravind