2017-08-12 34 views
0

我需要添加PipeTransform表示在對象數組屬性中的子字符串。我使用lodash時,過濾器是由名稱它會很好,像魅力的作品。但是當我更改名稱屬性到另一個,如標題。它的迴歸:lodash過濾器返回無法讀取屬性'indexOf'null

Cannot read property 'indexOf' of null

我管代碼:

import * as _ from 'lodash'; 
import { Pipe, PipeTransform } from '@angular/core'; 

@Pipe({ 
    name: 'dataFilterTitle' 
}) 
export class DataFilterPipeByTitle implements PipeTransform { 

    transform(array: any[], query: string): any { 
     debugger; 
     if (query) { 
      return _.filter(array, row=>row.title.indexOf(query) > -1); 
     } 
     return array; 
    } 
} 

錯誤:

ERROR TypeError: Cannot read property 'indexOf' of null 
at datafilterpipebyTitle.ts?071a*:12 
at arrayFilter (lodash.js:603) 
at Function.filter (lodash.js:9190) 
at DataFilterPipeByTitle.webpackHotUpdate.../../../../../src/app/plugins/datatable/datafilterpipebyTitle.ts.DataFilterPipeByTitle.transform (datafilterpipebyTitle.ts?071a*:12) 
at checkAndUpdatePureExpressionInline (core.es5.js:11350) 
at checkAndUpdateNodeInline (core.es5.js:12244) 
at checkAndUpdateNode (core.es5.js:12177) 
at debugCheckAndUpdateNode (core.es5.js:12880) 
at debugCheckDirectivesFn (core.es5.js:12821) 
at Object.eval [as updateDirectives] (ListComponent.html:17) 
+0

你可以發佈你的數組對象嗎? – CruelEngine

回答

1

錯誤清楚地表明無法讀取空的特性 '的indexOf',這意味着title財產有時可能是null。所以在做之前indexOf檢查title是否存在。

transform(array: any[], query: string): any { 
    if (query) { 
     return _.filter(array, row=> row.title && row.title.indexOf(query) > -1); 
    } 
    return array; 
} 
+0

OWW,謝謝。是我的錯! –