如何检查管道中未定义的项目?

时间:2016-05-19 14:24:04

标签: javascript typescript angular

我使用Angular2和自定义管道来过滤我的项目,如:

transform(value: any, args: string[]): any {
   if (args) {
         return value.filter(foo => foo.url.indexOf(args) != -1)
   };
   return value;
}

但我的一些foo.url项未定义,我收到此错误:

TypeError: Cannot read property 'indexOf' of undefined

如何检查属性是否未定义并将被过滤?

2 个答案:

答案 0 :(得分:1)

您正在使用 TypeScript ,因此现在是时候开始利用它带来的所有好处了。不要使用类型transform的参数编写此any函数,而是指定类型。这将有助于缓解像这样的愚蠢的运行时问题。您显然假设value参数是一个数组,因此将其声明为一个(我们对返回类型执行相同的操作)。那么它是什么类型的数组,让我们演示这个......而不是:

transform(value: any, args: string[]): any {
   if (args) {
         return value.filter(foo => foo.url.indexOf(args) != -1)
   };
   return value;
}

让我们这样写:

transform(value: Foo[], args: string[]): Foo[] {
   if (args) {
         return value.filter(foo => foo.url.indexOf(args) != -1)
   };
   return value;
}

然后我们可以有一个代表Foo的类:

export class Foo {
    constructor(url: string);
}

这将确保帮助防止运行时属性urlundefined的运行时问题。

答案 1 :(得分:0)

你可以试试这个:

/* mobile first */

.div1, .div2 {
  padding: 20px;
  margin-bottom: 10px;
}

.div1 {
  background-color: pink;
}

.div2 {
  background-color: tan;
}


@media screen and (min-width: 600px) {
  .div1{
    display: none;
  }
}