After receiving data from a HTTP Response, I am trying to access and display it in my template. However, despite storing the data into a component variable, I am encountering issues when trying to access specific properties of the object.
{
"files": [ ],
"posts": [
{
"content": "This is a test post related to Project 2.",
"id": 2,
"name": "Example Post 2",
"timestamp": "Wed, 10 Aug 2016 19:52:09 GMT"
}
],
"project": {
"id": 2,
"info": "This is the text for Example Project 2",
"name": "Example Project 2",
"timestamp": "Wed, 10 Aug 2016 19:50:59 GMT"
}
}
I have tried accessing the project id with {{project.project.id}}, but it does not work as expected. The object structure is displayed as follows:
Object { files: Array[0], posts: Array[1], project: Object }
Despite attempting various solutions such as iterating over the JSON object, I continue to face errors. Here is an exception message that was raised:
Uncaught (in promise): Error: Error in ./ProjectDetailComponent class ProjectDetailComponent - inline template:0:4 caused by: self.context.project is undefined
To provide more context, here are the relevant 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) {
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg);
return Observable.throw(errMsg);
}
}
Any assistance or guidance on resolving these issues would be greatly appreciated!