简体   繁体   中英

how to return a data from http call in angular 2 when the call is success

Take this function as example:

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),
      () => { }
    );
  }

What my understanding is, the return data.response.data will not actually return something when the getSessionInfo() is called.

For example, the this.session will still be undefined.

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

What I want to do is, return the value data.response.data and assign it to this.session.

Note, they are in different class in 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);
  }

}

The ApiService class is in a different folder

 @Injectable()
    export class ApiService {

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

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

I used to know they can do what I want using $q, $defer, but what should I do using Angular 2

Do return create either new Promise / Observable as you are going to use .subscribe over observable. So this._http.get(someCorrectUrlHere) promise from getSessionInfo method and then do have .then with Arrow function over getSessionInfo method.

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);
      },
      () => {}
    );
  });
}

Code

export class HeaderComponent {
  service: ApiService;
  session: Object;
  constructor(service: ApiService) {
    this.service = service;
    this.getSession();
  }

  getSession() {
    this.service.getSessionInfo().then(
    //success function.
    (session) => {
        this.session = session;
        console.log(session);
    }, 
    (error)=>{
       //error function
    });
  }
}

You can convert Observable returned by Angular 2 http call to Promise if you are comfortable working with that

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

More about it in the official Angular docs here .

Or, you can try to do it Angular 2 way. Keeping your service as

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

and subscribing in your 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),
     () => { }
   );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM