您如何调用一个在角度2中返回单个JSON对象的web服务?

时间:2022-05-22 12:15:36

Trying to call a webservice from Angular 2 that returns a single Json object:

尝试从角2调用返回单个Json对象的web服务:

{
   "fullDisplayName": "test",
   "result": "SUCCESS"
}

Below are the code snippets for my route:

以下是我的路线的代码片段:

Service

服务

getJsonObject () {
    return this.http.get(this.url)
                    .map(res => <jsonObject> res.json())
                    .do(jsonObject=> console.log(jsonObject))
                    .catch(this.handleError);
}

Component

组件

getJsonObject() {
   console.log('BEFORE')
   this.service.getJsonObject()
      .subscribe(
          jsonObject=> this.jsonObject = jsonObject,
          error =>  this.errorMessage = <any>error);
          console.log(this.jsonObject)
          console.log("AFTER")
 }

All that I get is a undefined object but I can see the JSON in the console log in chrome. The funny thing is I place a log in the component before and after the call, both those logs are displayed before the JSON found is displayed in log, making it look like it's somehow trying to map the object before the web service returns the data.

我得到的只是一个未定义的对象,但我可以在chrome的控制台日志中看到JSON。有趣的是,在调用之前和之后,我在组件中放置了一个日志,这两个日志都在JSON中显示之前显示,这使得在web服务返回数据之前,看起来好像在尝试映射对象。

Console Log

控制台日志

 Angular 2 is running in the development mode. Call enableProdMode() to enable the production mode.
 BEFORE
 undefined
 AFTER
 Object {fullDisplayName: "test", result: "SUCCESS"}

Any help is greatly appreciated.

非常感谢您的帮助。

1 个解决方案

#1


1  

     console.log(this.jsonObject)
     console.log("AFTER")

is executed before the request to this.url is even sent to the server. Observable is async and execution is enqueued into the event queue and when the response arrives the callback you passed to subscribe(...) is executed.

是在请求之前执行的。url甚至被发送到服务器。可观察性是异步的,执行被加入到事件队列中,当响应到达时,您传递给subscribe(…)的回调被执行。

This is what you actually need to do:

这就是你真正需要做的:

getJsonObject() {
   console.log('BEFORE')
   this.service.getJsonObject()
      .subscribe(
          jsonObject=> {
              this.jsonObject = jsonObject,
              console.log(this.jsonObject)
              console.log("AFTER")
          },
          error =>  this.errorMessage = <any>error);
 }

#1


1  

     console.log(this.jsonObject)
     console.log("AFTER")

is executed before the request to this.url is even sent to the server. Observable is async and execution is enqueued into the event queue and when the response arrives the callback you passed to subscribe(...) is executed.

是在请求之前执行的。url甚至被发送到服务器。可观察性是异步的,执行被加入到事件队列中,当响应到达时,您传递给subscribe(…)的回调被执行。

This is what you actually need to do:

这就是你真正需要做的:

getJsonObject() {
   console.log('BEFORE')
   this.service.getJsonObject()
      .subscribe(
          jsonObject=> {
              this.jsonObject = jsonObject,
              console.log(this.jsonObject)
              console.log("AFTER")
          },
          error =>  this.errorMessage = <any>error);
 }