I need to store a JSON response that includes an array with the following data:
0 : {ID: 2, NAME: "asd", PWD_EXPIRY_IN_DAYS: 30}
1 : {ID: 1, NAME: "Admin", PWD_EXPIRY_IN_DAYS: 30}
In my code, I have defined a local variable called groups of type Group as shown below:
export class Group {
id: string;
name: string;
pwd_expiry_in_days: string;
}
The issue arises when I try to assign the JSON response to an object of type Group in my component. The current implementation is not working and displays 'undefined'. Here is the section of code causing the problem:
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
}
How can I resolve this issue? It seems to be related to an Async problem where simply assigning data to this.roles does not work and results in 'undefined' outside the subscription scope in my component.
What would be the correct approach to assigning a response to my local variable in this scenario?
An updated template has been added to view the object, but it still shows up as undefined:
<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>
Thank you!