Http Api 调用承诺的响应未定义 - Angular 2

Response of Http Api call promise is undefined - Angular 2

我在 WebAPI 中创建了一个 api,如下所示。

public HttpResponseMessage Get() {

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

我正在尝试从 Angular 调用它,如下所示

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 调用完成:未定义

有人可以帮忙吗?

谢谢

尝试在此处使用简单的承诺。

在Service.ts(演示服务)

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

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

}