2017-10-09 6 views
0

にHTTPレスポンスをマッピングできません。Chromeコンソールに次のコードが返されます。ERROR TypeError: t.json(...).map is not a functionng serve -prodng test --sm=falseは正常に動作します。Interface to

結果をInterfaceのモデルにマップし、HTMLで出力したいと考えています。

.... 
export interface UsersData { 
    _id: number; 
    email: string; 
    fullName: string; 
} 
export class RetrieveUsrData { 
    private issuesUrl = 'http://localhost:4000/users'; 
    getUserDetails(): Observable<UsersData[]> { 
     return this.http.get(this.issuesUrl) 
         .map(this.extractData) 
    } 

    extractData(result: Response): UsersData[] { 
     console.log(JSON.stringify(result.json())); 
     return result.json().map(usr => { 
      return { 
       _id: usr.message._id, 
       email: usr.message.email, 
       fullName: usr.message.fullName 
      } 
     }).subscribe(result => result = result); 
    } 
    constructor(private http: Http) {} 
} 
... 

私はいくつかの問題をチェックしています。 mapping a HTTP response to a JSON and then mapping the JSON to a model、とに私のコード/方法を変更:

extractData(result: Response): UsersData[] { 
    return result.json().map(res => ({ 
     _id:res.message._id, 
     email:res.message.email, 
     fullName:res.message.fullName 
    }) as UsersData) 
    .subscribe(result => result = result); ; 
} 

が、私は同じエラーを取得しておきます。

+1

「http:// localhost:4000/users」からの応答は何ですか? API –

+0

@PankajParkar:これは 'http:// localhost:4000/users' APIのレスポンスです: ' {"エラー":false、 "message":[{"_id": "523"、 "email" "fullName": "xxxxx yyyyy"}、{"_id": "594"、 "email": "[email protected]"、 "fullName": "xxxx yyyyy"}、{[email protected] " "_id": "88"、 "email": "[email protected]"、 "fullName": "xxxx yyyyy"}、{"_id": "59"、 "email": "[email protected]" 、 "fullName": "xxxx yyyyy"}]} '。しかし、今修正されました。ありがとう! –

+0

私は同じと思った。 @Fentonはすでにそれに答えました。ありがとう:) –

答えて

1

.mapメソッドはオブジェクトではなく配列で使用できます。

あなたのエラーの原因として最も可能性が高いが、あなたがこのような応答があればということである。

{ 
    someKey: [1, 2, 3, 4] 
} 

をあなたが使用する必要があります:

result.json().someKey.map(//... 

そして、あなたも簡単に使用することができる可能性が

return <UsersData[]>result.json().someKey; 
+0

ここに私の応答です: '{ "エラー ":偽、 "メッセージ ":[{" _id ":" 523 "、" email ":" [email protected] "" fullName ":" xxxx yyyyy "}、 {" _id ":" 594 "、" email ":" [email protected] "、" fullName ":" xxxx yyyyy "}、 {" _id " ""、 "email": "[email protected]"、 "fullName": "xxxx yyyyy"}、 ":" xxxx yyyyy "} ] } –

+1

素晴らしい!私の悪い。 JSONレスポンスの 'message'キーをキャッチすることができませんでした。あなたが言ったように、 'map()'は '配列 '上で実行されなければなりません。だから、私の応答 'message'はオブジェクトの配列です。私の日を救った。 –

+0

ご質問ください。 '_id'キーの値をJSONオブジェクトから他のコンポーネントに渡すための最良の方法は何でしょうか。それは?@Input()_id'ですか、それともサービスの一種を使って解決するのでしょうか?ありがとう。 –