2016-12-20 1 views
0

enter image description hereenter image description here私は私のオブジェクトをサーバーレスポンスから返しました。これはgoogle chrome開発ツールのネットワークタブに表示されます。node-expressサーバーの応答を見ることができますが、私はそれを私のangular2 promiseサービスで使用できません。

module.exports = (req, res) => { 
var obj = { 
    name: "Thabo", 
    age: 23 
}; 
res.json({obj}) 
}; 

そして私は、私も「し、」約束の上の応答を記録し、それをログに記録し

export class MyService { 
    constructor(private http: Http) { } 
    getMessage(): Promise<any> { 
return this.http.get('/map-moving-agents') 
      .toPromise() 
      .then((res)=> { 
      console.log(res.json().data); 
      res.json().data; 
      }) 
      .catch(this.handleError); 
} 

private handleError(error: any): Promise<any> { 
console.error('An error occurred', error); 
return Promise.reject(error.message || error); 
} 
} 

サーバーから観察可能な応答を取得するために約束を使用していますangular2-typescriptですサービスを持っています未定義。

そして、これが

export class MapMovingAgents implements OnInit{ 

msg: {}; 
constructor(private myService: MyService){} 

getMessage(): void { 
    this.myService.getMessage().then((res) => { this.msg = res;}) 
    console.log(this.msg); 
} 

ngOnInit(): void { 
    this.getMessage(); 
} 
} 
+0

res.json().objundefined帰りでウィルdataフィールドを持っていませんか? – echonax

+0

は、私はちょうど追加したIVEはIVEはそれを試して助けない – Teebo

+0

サイモン? return文を 'res.json()。data'と' console.log'に追加します。 – echonax

答えて

1
getMessage(): void { 
    this.myService.getMessage().then((res) => { this.msg = res;}) 
    console.log(this.msg); 
} 

undefinedgetMessage()ためにログに記録されます関数はasync関数です。

getMessage(): void { 
    this.myService.getMessage().then((res) => { 
     this.msg = res; 
     console.log(this.msg); 
    });   
} 

そして、あなたの応答へ

変更それはそうres.json().data;あなたが応答してネットワーク]タブのスクリーンショットを追加することができる唯一のres.json()または

+0

それを試してみました – Teebo

+0

@Teeboどのように私の答えを組み合わせることについて、@を助けていない私はその – echonax

+0

これはまさに私がやったことです。 – Teebo

1

は、あなたが使用するようにコードの残りの部分のための最終的な値を返す必要がサービスを使用するコンポーネントである

return this.http.get('/map-moving-agents') 
     .toPromise() 
     .then((res)=> { 
     console.log(res.json().data); 
     return res.json().data; <-------------- 
     }) 
     .catch(this.handleError); 
} 
+0

について両者は今申し訳ありません持っているネットワーク]タブ – Teebo

関連する問題