简体   繁体   中英

How can I map json response into array angular2

My response is getting mapped to undefined, I console log the response perfectly, but whenever I console log the array/json object they get set to undefined. Here is my code:

  public roles: any;


   private getGroups() {
     console.log("In Groups");
    let _url = "GroupsURL";
    let headers = new Headers();
    headers.append('X-User', sessionStorage.getItem('username'));
    headers.append('X-Token', sessionStorage.getItem('token'));
    headers.append('X-AccessTime', sessionStorage.getItem('AccessTime'));
    headers.append('Content-Type', 'application/json');
    let options = new RequestOptions({ headers: headers });

    return this.http.get(_url, options)
    .toPromise().then(response => {
      this.roles = response.json();
    })
  }

then in main I console log roles and it gets to be undefined

here is the constructor

 constructor() {
this.getGroups();
console.log(this.roles); <-- returns undefined

roles contains the same model as the json response containing the same data members such as:

    export class Group {
    id: string;
    name: string;
    pwd_expiry_in_days: string;
}

When I console log the response within the return, it logs the response perfectly, why is it out of scope from my main?

I can provide more details if needed. My main goal is to get from my server data and map it to my front end form to provide a list of roles to assign.

thank you!

Code is async. But you work with code like it is sync. That will not work. Since that you need this:

  constructor() {
      this.getGroups()
        .then(roles => this.roles = roles); // <-- here you set internal roles property
      // ....
   }


   private getGroups() {
     console.log("In Groups");
    let _url = "GroupsURL";
    let headers = new Headers();
    headers.append('X-User', sessionStorage.getItem('username'));
    headers.append('X-Token', sessionStorage.getItem('token'));
    headers.append('X-AccessTime', sessionStorage.getItem('AccessTime'));
    headers.append('Content-Type', 'application/json');
    let options = new RequestOptions({ headers: headers });

    return this.http.get(_url, options)
    .toPromise()
    .then(response => response.json())
  }

Note : promises is not Angular (2+) way :) Observables now do this work.

Example with observables:

constructor() {
  this.getGroups()
    .subscribe(roles => this.roles = roles);
  }
}

private getGroups(): Observable<any> {
  // ....
  return this.http.get(_url, options)
    .map(response => response.json())
}

Don't worry about firing of fn you pass to subscribe more than 1 time. Http service always returns an observable which fires only 1 time.

Also check HttpClient service. It is new Angular API for Http calls. At least you don't need to call json() method on response each time =). More reading: https://angular.io/guide/http

Actually, Angular docs is perfect. A lot of useful things described there.

Chek out offictial docs for more examples and information: https://angular.io/tutorial/toh-pt6#observables

It is async method and promise value is return also in a different time. When you call getGroups() method because of returning promise value. You need to get value in then () or have to use again then () to make sequential procedures like below;

private getGroups() {
     console.log("In Groups");
    let _url = "GroupsURL";
    let headers = new Headers();
    headers.append('X-User', sessionStorage.getItem('username'));
    headers.append('X-Token', sessionStorage.getItem('token'));
    headers.append('X-AccessTime', sessionStorage.getItem('AccessTime'));
    headers.append('Content-Type', 'application/json');
    let options = new RequestOptions({ headers: headers });

    return this.http.get(_url, options)
    .toPromise().then(response => {
      this.roles = response.json();
      console.log(this.roles);    // It will work

    })
    .then( data => {
     console.log(data);    // it also works
     }
  }

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