2017-07-26 4 views
1

私は以下のようにWebAPIでapiを作成しました。ランニングでHTTP API呼び出しの応答が未定義です - 角2

export class AppComponent implements OnInit { 

    data2: String; 
    constructor(private s: DemoService){} 

    ngOnInit(){ 

    this.s.GetHttpData().subscribe(data=>this.data2=data); 
    console.log("Http call completed: "+this.data2); 

} 

:私は

Service.ts

@Injectable() 
export class DemoService { 

    constructor(private http:Http){} 

    GetHttpData(){ 

     return this.http.get('http://localhost:54037/api/home') 
     .map((res:Response)=>res.json()); 
    } 

コンポーネント以下のように角度からそれを呼び出すようにしようとしています

public HttpResponseMessage Get() { 

      var response = Request.CreateResponse(HttpStatusCode.OK); 
      response.Content = new StringContent(JsonConvert.SerializeObject("Hello World"), Encoding.UTF8, "application/json"); 
      return response; 
     } 

アプリケーションは、私は出力を得る:完成

HTTP呼び出し:未定義

は、誰かがこれを助けることはできますか?

ありがとうございました

+1

可能な重複https://stackoverflow.com/questions/43055706/how-do-i-return-the -response-from-observable-http-async-call-in-angular2) – Alex

+0

[非同期呼び出しからの応答を返すにはどうすればよいですか?](https://stackoverflow.com/questions/14220321/how -do-i-return-from-as-asynchronous-call) – Igor

+0

コードで予想される動作である重複を参照してください。 'console.log'文を' subscribe'コールバックの中に入れます。提案された複製を読んで、javascript/typescriptの非同期コードの基本を理解してください。 – Igor

答えて

1

は、データ関数内console.logを置きます。

このようにお試しいただけますか?

export class AppComponent implements OnInit { 

    data2: String; 
    constructor(private s: DemoService){} 

    ngOnInit(){ 

    this.s.GetHttpData().subscribe(data=>{ 
     this.data2=data; 
     console.log("Http call completed: "+this.data2) 
    }); 

} 
[私はangular2において観察/ HTTP /非同期呼び出しからの応答を返すにはどうしますか?](の
+0

これは機能します。ありがとう –

+0

重複した質問とは何かを読んでください... https://meta.stackexchange.com/questions/10841/how-should-duplicate-questions-be-handled – Alex

+0

@ AJT_82私がそこに答えるうちに重複しているフラグはネットワーク上の問題ではありません。 – k11k2

0

ここで簡単にお約束してください。 Service.tsで

(DemoService)

GetHttpData() { 

     return new Promise(resolve => { 

      this.http.get('http://localhost:54037/api/home') 
       .map(res => res.json()) 
       .subscribe(data => { 
      resolve(data); 
     }); 
    } 

、コンポーネントで:

this.s.GetHttpData() 
     .then(data => { 
      console.log("Http call completed: "+data); 
}); 
+0

https://meta.stackexchange.com/questions/10841/how-should-duplicate-questions-be-handled – Alex

関連する問題