2017-07-26 75 views
1

我已经在WebAPI中创建了api,如下所示。Http Api呼叫承诺的响应是未定义的 - Angular 2

public HttpResponseMessage Get() { 

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

我试图从角称其为以下

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()); 
    } 

组件:

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); 

} 

在运行应用程序中,我得到的输出:

HTTP调用完成:未定义

有人能帮助呢?

谢谢

+1

的[我如何返回从angular2可观察/ HTTP /异步调用的响应?(可能的复制https://stackoverflow.com/questions/43055706/how-do-i-return-the -response-from-an-observable-http-async-call-in-angular2) – Alex

+0

[我如何从异步调用返回响应?](https://stackoverflow.com/questions/14220321/how -do-i-return-the-an-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) 
    }); 

} 
+0

This Works。谢谢 –

+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