当呼叫成功时,如何以角度2从http呼叫返回数据

时间:2016-04-05 21:45:49

标签: javascript angularjs promise angular

以此功能为例:

getSessionInfo() {
     this._http.get(someCorrectUrlHere)
     // Don't know what this map function do
    .map(res => res.json())
    // Don't know what this subscribe function do
    .subscribe(
      data => {
        if (data.response.statusCode === 200) {
           ** the data.response.data in this case is an object**
           return data.response.data;
        } else {
          console.log("cant get session info");
        }
      },
      err => console.log(err),
      () => { }
    );
  }

我的理解是,return data.response.data在调用getSessionInfo()时实际上不会返回某些内容。

例如,this.session仍然未定义。

  getSession() {
    this.session = this.service.getSessionInfo();
 }

我想要做的是,返回值data.response.data并将其分配给this.session。

注意,它们在Angular2 Project中属于不同的类。

export class HeaderComponent {

  service: ApiService;

  session: Object;

  constructor(service: ApiService) {
    this.service = service;
    this.getSession();
  }

  getSession() {
    this.session = this.service.getSessionInfo();

    // I expect this is the true value I expected, not undefined
    console.log(this.session);
  }

}

ApiService类位于不同的文件夹中

 @Injectable()
    export class ApiService {

      _http: Http;
      regions: Object;
   constructor(http: Http) {
    this._http = http;
  }

    getSessionInfo() {
    .......
  }
}

我曾经知道他们可以使用$ q,$ defer做我想做的事,但是我应该怎么做才能使用Angular 2

2 个答案:

答案 0 :(得分:3)

请返回创建<VirtualHost *:80> ServerName localhost DocumentRoot "d:/apache_test/htdocs/webapp" ProxyPreserveHost On ProxyRequests Off ProxyPass /tomcatapp http://localhost:8080/tomcatapp ProxyPassReverse /tomcatapp http://localhost:8080/tomcatapp </VirtualHost> / new Promise,因为您将使用Observable而不是observable。因此.subscribe承诺来自this._http.get(someCorrectUrlHere)方法,然后getSessionInfo .then优先于Arrow function方法。

getSessionInfo

<强>代码

getSessionInfo() {
  //creating custom promise & then resolving and rejecting it on condition.
  return new Promise((resolve, reject) =>{
    this._http.get(someCorrectUrlHere)
      .map(res => res.json())
      .subscribe(
      data => {
        if (data.response.statusCode === 200) {
          resolve(data.response.data); //returning data by resolving promise
        } else {
          console.log("cant get session info");
          reject("Error occured");
        }
      },
      err => {
        console.log(err);
        reject(err);
      },
      () => {}
    );
  });
}

答案 1 :(得分:1)

你可以将Angular 2 http调用返回的Observable转换为Promise,如果你习惯使用它

getSessionInfo() {
    return this._http.get(someCorrectUrlHere).toPromise();
);

有关官方Angular文档here的更多信息。

或者,您可以尝试使用Angular 2方式。保持您的服务

getSessionInfo() {
    this._http.get(someCorrectUrlHere)
    .map(res => res.json())
}

并在HeaderComponent中订阅

getSession() {
    this.service.getSessionInfo().subscribe(
    data => {
        if (data.response.statusCode === 200) {
           this.session = data.response.data; 
           console.log(this.session);
        } else {
           console.log("cant get session info");
        }
     },
     err => console.log(err),
     () => { }
   );
}