AJT_82 AJT_82 - 1 year ago 118
HTTP Question

HTTP: Assign json to local variable (angular2+ts rc5)

Not sure if my title would be correct for this, I'm a newbie.

When doing http calls, I would like to assign the incoming json to a local variable in my component. At the moment I also have a compile error I'm trying to figure out. The code still works though, but this should be linked to my actual problem.

I've tried to showcase the relevant parts of my code.


return this.http.get('someUrl')
.map((res: Response) => res.json())


template: `
<tr *ngFor="let acase of cases" >

export class CaseListComponent implements OnInit {

//local variable, need to have use of this!
acase: Case;
cases: Case[];

constructor(public _service: CaseService, public _route: ActivatedRoute) {


ngOnInit() {
.subscribe(cases => this.cases = cases);
console.log(this.cases) // undefined!!

ngAfterContentInit() {
console.log("cases: ", this.cases) //undefined!


So code works as should and displays the cases as it should, but I get compile error in
, at
where it says:

Type '{}' is not assignable to type 'Case[]'.
Property 'length' is missing in type '{}'.

But as said, it does work. But how could I fix this and most importantly, how do I assign the data to the local variables, as I need use them, but as is they are undefined!

Thanks for any help!

Answer Source

you are assigning cases in the callback and the console.log will run before callback finishes. hence you are getting undefined.

ngOnInit() {
            .subscribe(cases => {
             this.cases = cases;
             console.log(this.cases) // will print values...
        console.log(this.cases) // undefined!!

Similar is case for ngAfterContentInit it will run before callback returns hence undefined.

Hope this helps!!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download