我已经在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调用完成:未定义
有人能帮助呢?
谢谢
的[我如何返回从angular2可观察/ HTTP /异步调用的响应?(可能的复制https://stackoverflow.com/questions/43055706/how-do-i-return-the -response-from-an-observable-http-async-call-in-angular2) – Alex
[我如何从异步调用返回响应?](https://stackoverflow.com/questions/14220321/how -do-i-return-the-an-asynchronous-call) – Igor
查看重复项,这是您的代码的预期行为。将'console.log'语句*放在* subscribe'回调中。通读建议的重复项,以便了解javascript/typescript中异步代码的基本原理。 – Igor