Lelsoos Lelsoos - 2 months ago 14
TypeScript Question

Cant access deep level objects in HTTP Response

I've got this data from a HTTP Response

{
"files": [ ],
"posts": [
{
"content": "Dies ist ein Test-Posting, das zum Projekt 2 gehört.",
"id": 2,
"name": "Beispiel Post 2",
"timestamp": "Wed, 10 Aug 2016 19:52:09 GMT"
}
],
"project": {
"id": 2,
"info": "Dies ist der Text für das Beispiel Projekt 2",
"name": "Beispiel Projekt 2",
"timestamp": "Wed, 10 Aug 2016 19:50:59 GMT"
}
}


Its stored into a component variable and now I want to access it in my template. I tried to do something like this:

{{project.project.id}}


It does not work. The object is stored like that:

Object { files: Array[0], posts: Array[1], project: Object }


I already tried out solutions like this: iteration a json object on Ngfor in angular 2 but it wont help.

Heres the exception I got:

Uncaught (in promise): Error: Error in ./ProjectDetailComponent class ProjectDetailComponent - inline template:0:4 caused by: self.context.project is undefined


For more details, here are the files:

Component:

@Component({
selector: 'app-project-detail',
templateUrl: './project-detail.component.html',
styleUrls: ['./project-detail.component.sass']
})
export class ProjectDetailComponent implements OnInit {
private project;
private errorMessage;

constructor(private route: ActivatedRoute,
private router: Router,
private projectService: ProjectsService) {
}

ngOnInit() {
this.route.params.forEach((params: Params) => {
let id = +params['id'];
this.projectService.getProjects(id).subscribe(
function (project) {
this.project = project;
},
error => this.errorMessage = <any>error
);
});
}

}


Service:

@Injectable()
export class ProjectsService {

constructor(private http: Http) {}

private projectsUrl = 'http://localhost:2000/api/projects/';

getProjects(id?: number): Observable<any>{
if(id){
return this.http.get(this.projectsUrl + ""+id)
.map(this.extractData)
.catch(this.handleError);
} else {
return this.http.get(this.projectsUrl)
.map(this.extractData)
.catch(this.handleError);
}


}

private extractData(res: Response) {
let body = res.json();
return body;
}
private handleError (error: any) {
// In a real world app, we might use a remote logging infrastructure
// We'd also dig deeper into the error to get a better message
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);
}
}


I appreciate any help!

Answer

The value is not assigned to where you thing it is.

ngOnInit() {
    this.route.params.forEach((params: Params) => {
        let id = +params['id'];
        this.projectService.getProjects(id).subscribe(

            // function (project) {
            // should be
            (project) => {             // <<<<=== change
                this.project = project;
            },
            error => this.errorMessage = <any>error
        );
    });
}

and use it with

{{project?.project?.id}}
Comments