AJT_82 AJT_82 - 2 months ago 14
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.

Service:

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


Component:

@Component({
template: `
<h1>Cases</h1>
<hr>
<br>
<table>
<tr *ngFor="let acase of cases" >
<td>{{acase.name}}</td>
</tr>
</table>
`,
})

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() {
this._service.getCases()
.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
ngOnInit
, at
this.cases
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

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

ngOnInit() {
        this._service.getCases()
            .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!!