如何将局部变量分配给json响应angular2

时间:2017-08-30 09:15:41

标签: json angular typescript

我想分配一个包含以下数组的json响应:

  

0   :   {ID:2,NAME:" asd",PWD_EXPIRY_IN_DAYS:30}

     

1   :   {ID:1,NAME:" Admin",PWD_EXPIRY_IN_DAYS:30}

我有一个类型为group的局部变量,就像这样

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

现在我在我的组件中创建了一个Group类型的对象,我想将json的回复分配给,以下是无效的,并且显示未定义。这是我的代码:

    import { Injectable, Provider, ModuleWithProviders,Component, OnInit } from '@angular/core';
import { Http, Headers, Response, RequestOptions } from '@angular/http';

import { Observable } from 'rxjs/Observable';
import {Group} from '../../_models/group'
import 'rxjs/add/operator/map';


interface Validator<T extends FormControl> {
  (c: T): { [error: string]: any };
}

@Component({
  selector: 'form1',
  templateUrl: './form1.html',
  moduleId: module.id,
})
export class Form1Component {

  public roles: Group; // <--- variable to feed response into


   private getGroups() : Observable<any> {
    console.log("In Groups");
    var responseAsObject : any;
    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)
    .map(response => {
      var responseAsObject = response.json();
      console.log(responseAsObject); //<--- proper response
      return responseAsObject;
    })
}


  constructor(private http: Http) {

    this.getGroups()
    .subscribe(data => {
      this.roles = data;
      console.log(this.roles); //<--- proper response
    });

    console.log(this.roles); //<----- undefined, I need the roles variable so I can use it on the front end

}

我该如何解决这个问题?我被告知它是一个异步问题,只是分配this.roles = data(来自json响应)不起作用,并在我的组件中显示为未定义(在订阅范围之外的任何地方)。

在这种情况下,将响应分配给我的局部变量的正确方法是什么?

使用模板更新以查看对象,也被视为未定义:

        <div class="form-group" [ngClass]="{'has-error':!complexForm.controls['group_id'].valid}">
      <label>Group ID</label>
      <div class="row">
        <div class="col-md-4">
          <select name="group_id" id="group_id" class="form-control" [formControl]="complexForm.controls['group_id']" data-width='200px'>
    <option *ngFor="let role of roles" [value]="role.id">  
    {{role.name}}
    </option>
  </select>
        </div>
      </div>
    </div>
谢谢你!

2 个答案:

答案 0 :(得分:1)

  

在这种情况下,将响应分配给我的局部变量的正确方法是什么?

你没有做错。您只需要为组件构造的初始阶段undefined和/或为空而做好准备。

最简单的方法是在迭代之前在html节点上执行*ngIf="someArray.length"。类似的东西:

// html
...
<div class="row" *ngIf="roles.length"><!-- Prevents un-populated array iteration -->
    <div class="col-md-4">
        <select class="form-control">
            <option *ngFor="let role of roles" [value]="role.id">
                {{role.name}}
            </option>
        </select>
    </div>
</div>

您可以对打字稿进行一些改进,例如不更改数组的指针 - 这可能会在以后节省您的麻烦 - 而不是this.roles = data,使用this.roles.length = 0; this.roles.push(...data); 。欲了解更多信息,请阅读Angular Change Detection

// ts
export class Form1Component implements OnInit{
    public roles: Array<Group> = []; // <--- isn't this an Array?
    ...
    private getGroups() : Observable<any> {
        var responseAsObject : any;
        ...
        return this.http.get(_url, options)
            .map(response => {
                var responseAsObject = response.json();
                return responseAsObject;
            });
    }

    constructor(private http: Http) {}

    ngOnInit(){
        this.getGroups()
            .subscribe(data => {
                let groups = data.map(item=>{
                                return new Group(item)
                             });//<--- If you want it to be of type `Group`
                this.roles.length = 0;
                this.roles.push(...groups);
            });
    }
    ...
}

答案 1 :(得分:0)

您的第二个控制台日志将在您的api调用之前运行,因为api调用是异步的。请尝试将角色类型设为publice role: any,如果它有效,则必须修改您的群组模型。