2017-08-12 77 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,谢谢。是我的错! –