【问题标题】:Response of Http Api call promise is undefined - Angular 2Http Api 调用承诺的响应未定义 - Angular 2
【发布时间】:2017-07-27 23:41:29
【问题描述】:

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

有人可以帮忙吗?

谢谢

【问题讨论】:

标签: angular asp.net-web-api angular-promise


【解决方案1】:

console.log放在data函数里面。

你可以这样试试。

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

}

【讨论】:

【解决方案2】:

在这里尝试使用一个简单的承诺。

在 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);
});
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-25
  • 1970-01-01
  • 2017-08-04
相关资源
最近更新 更多