我在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 调用它,如下所示
服务网
@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 调用已完成:未定义
有人可以帮忙吗?
谢谢
将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)
});
}
尝试在这里使用一个简单的承诺。
In 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);
});