简体   繁体   English

我如何将json响应映射到数组angular2

[英]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. 我的响应被映射为未定义,我以控制台方式完美地记录了响应,但是每当我以控制台方式记录阵列/ json对象时,它们就会被设置为未定义。 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: 角色包含与json响应相同的模型,其中包含相同的数据成员,例如:

    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. 注意 :promises不是Angular(2+)方法:) Observables现在可以完成这项工作。

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. 不必担心您通过订阅超过1次的fn被解雇。 Http service always returns an observable which fires only 1 time. Http服务始终返回仅触发1次的Observable。

Also check HttpClient service. 还要检查HttpClient服务。 It is new Angular API for Http calls. 这是用于Http调用的新Angular API。 At least you don't need to call json() method on response each time =). 至少您不需要每次都在响应时调用json()方法=)。 More reading: https://angular.io/guide/http 更多阅读: https : //angular.io/guide/http

Actually, Angular docs is perfect. 实际上,Angular文档是完美的。 A lot of useful things described there. 那里描述了很多有用的东西。

Chek out offictial docs for more examples and information: https://angular.io/tutorial/toh-pt6#observables 查阅官方文档以获取更多示例和信息: https ://angular.io/tutorial/toh-pt6#observables

It is async method and promise value is return also in a different time. 这是一个异步方法,并且promise值也在不同的时间返回。 When you call getGroups() method because of returning promise value. 当您由于返回承诺值而调用getGroups()方法时。 You need to get value in then () or have to use again then () to make sequential procedures like below; 您需要在then()中获取价值,或者必须再次使用then()来进行如下所示的顺序过程;

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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