2016-12-06 88 views
1

我有一個Angular 2應用程序,我已經實現了一個管道來基本檢查一些空值。問題是,當我使用map()我得到下面的錯誤:使用Angular 2&Typescript的地圖()錯誤

core.umd.js:2838 EXCEPTION: Uncaught (in promise): Error: Error in app/components/performances/performances.component.html:18:10 caused by: Cannot read property 'map' of undefined 
TypeError: Cannot read property 'map' of undefined 

下面你可以看看我的代碼:

import { Pipe, PipeTransform } from '@angular/core'; 
import {Performance} from '../common/performance'; 

@Pipe({ 
    name: 'defaultPerformanceValueIfNull' 
}) 

export class PerformanceCheckValuesPipe implements PipeTransform { 
    transform(values: Performance[]): any { 
      let performances = values.map(function(p) { 
       return Object.assign(p, 
        { 
         OneMonthBack: p.OneMonthBack || '-', 
         ThreeMonthsBack: p.ThreeMonthsBack || '-' 
        }) 
      }); 
      return performances; 
     } 
} 

我認爲的代碼是好的,你可以看看一個例子,我寫在這裏: link

任何想法它與我的代碼? 謝謝!

+0

您是否嘗試過導入地圖運算符。即.....'導入'rxjs/add/operator/map''或導入所有運算符'import'rxjs/Rx';' – Bean0341

回答

2

這樣做,使您的管道更加防彈!

好像在第一次管道轉換時輸入數據未定義!

export class PerformanceCheckValuesPipe implements PipeTransform { 
    transform(values: Performance[]): any { 
     if (!values || !values.length) return []; 

     return values.map(p => Object.assign(p, { 
      OneMonthBack: p.OneMonthBack || '-', 
      ThreeMonthsBack: p.ThreeMonthsBack || '-' 
      }) 
    ); 
    } 
} 
+0

謝謝@mxii它的工作正常,你告訴我的改變,但我不'不明白爲什麼我必須這樣做。我只在一個地方使用管道..對我來說沒有意義。 – gon250

+1

這是你想要'變換'的數據的原因是在第一次變化檢測'undefined'期間。假設你的變量是這樣的'values:number [];'。它的未定義,並將通過http.get或類似的東西聲明..你可以改變它'values:number [] = [];'。 – mxii