After running through many tutorials on tinterweb I have finally started to try and build something useful to me using Angular2 and I have come across my first issue. I can
In fact, it's because your data are loaded asynchronously. So within the constructor of your component, you initially get an undefined value.
constructor(private _friendService: FriendService) {
this.friends = _friendService.getFriends();
}
To keep your constructor like that, you need to refactor your code to make the getFriends
method of your service return an observable:
@Injectable()
export class FriendService {
constructor(private http:Http) {
}
getFriends() {
return this.http.request('./data/people.json')
.map(res => res.json());
}
}
Then you can use the async
pipe into your component template:
template: `
<h1>Hello from the {{ componentName }}!</h1>
<div *ngFor="#f of friends | async">
<h3>Name: {{ f.name }}</h3>
<h4>Age: {{ f.age }}</h4>
</div>
`