2017-10-02 4 views
1

戻り値に単一オブジェクトが1つしかない場合は、.json()から返される応答で.filter()メソッドが機能しません 。私はこの問題にどのように対処するかわかりません。角度のある.filter()がJSONレスポンスで動作しない

getFavorites() { 
const userId = this.authService.getActiveUser().uid; 
return this.http.get(this.databaseAddress + userId + '.json') 
    .map(
    (response: Response) => { 
    return response.json(); 
    }) 
    .do(
    (data) => { 
     if(data) { 
     this.favorites = data; 
     }else { 
     this.favorites = []; 
     } 
    }) 

}

this.favoritesService.getFavorites() 
    .subscribe(
     (list: Recipe[]) => { 
     if(list) { 
      this.favoriteRecipes = list.filter(
      item => item !== null 
     ); 
     } else { 
      this.favoriteRecipes = []; 
     } 
     } 
    ); 

エラーが返さ:APIから返されていないデータの場合

ERROR TypeError: list.filter is not a function 
+2

。 FilterはJS配列メソッドです。配列を持たない場合は使用できません。 – jonrsharpe

+0

これを回避する方法はありますか? –

+0

空の配列を作成し、jsonが登録する前にmap関数で応答するiterating jsonを埋めます。だから毎回json配列を返すことができます。 –

答えて

0

を、あなたの応答がnull/emptyになります。 filter操作はArray型でのみ動作します。 map演算子から[]空の配列を返すことを検討してください。

getFavorites() { 
const userId = this.authService.getActiveUser().uid; 
return this.http.get(this.databaseAddress + userId + '.json') 
    .map(
    (response: Response) => { 
     return response.json() || []; // return blank [] if data is null or empty 
    }) 
    .do(
    (data) => { 
     if(data) { 
     this.favorites = data; 
     }else { 
     this.favorites = []; 
     } 
    }) 
} 
+0

こんにちは、私はすでに私が提供したコードの第2ブロックでこの状況を処理していることがわかります。ここでの問題は、応答がnull /空の場合ではなく、応答にオブジェクトが1つしかない場合です。 –

0

ここでの問題は、応答がnull /空の場合ではなく、応答にオブジェクトが1つしかない場合です。ちょうどあなたが空の配列を持っている、とあなたが行われているものは何でも結果追加

...角とは何の関係もないのです

getFavorites() { 
const userId = this.authService.getActiveUser().uid; 
return this.http.get(this.databaseAddress + userId + '.json') 
    .map(
    (response: Response) => { 
    return response.json(); 
    }) 
    .do(
    (data) => { 
     if(data) { 
     this.favorites = [].push(data); 
     }else { 
     this.favorites = []; 
     } 
    }) 
関連する問題