I am pretty new to angular 2, what I am trying to accomplish is simple:
- Get the category id passed in via routing
- Call API with category id
- Populate variable "category" with data returned from API and display the category name
My view is simple:
<h3>{{category.name}}</h3>
Component code:
import { Component, Inject } from '@angular/core';
import { Http } from '@angular/http';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'browse-category',
template: require('./browse-category.component.html'),
styles: [require('./browse-category.component.css')]
})
export class BrowseCategoryComponent {
products: IProduct[];
category: ICategory;
categoryId: number;
constructor(private route: ActivatedRoute, private http: Http, @Inject('ORIGIN_URL') private originUrl: string) {
}
ngOnInit(): void {
this.route.params.subscribe(params => {
this.categoryId = +params['categoryId'];
// get category details
this.http.get(this.originUrl + '/api/Category/' + this.categoryId).subscribe(result => {
var data = result.json().data;
if (data != null && result.status === 200) {
this.category = data;
console.log(this.category);
}
});
});
}
}
If I disable the view output, i am able to see the console.log output, if I don't I get the following error:
NodeInvocationException: Uncaught (in promise): TypeError: Cannot read property 'name' of undefined TypeError: Cannot read property 'name' of undefined
I assume it's because the promise hasn't returned yet. Ideally what's the best approach to fix this?