[Angular 2] 4. Inject service into component

Before we get too much further, we should mention that putting our model (array) directly in our controller isn't proper form. We should separate the concerns by having another class serve the role of model and inject it into the controller.

Make a FriendsService class to provide the model with the list of friends.

 

import {Component, View, bootstrap, NgFor} from 'angular2/angular2';
class FriendsService {
    names: Array<string>;
    constructor() {
        this.names = ["Aarav", "Martin", "Shannon", "Ariana", "Kai"];
    }
}

@Component({
    selector: 'display',
    appInjector: [FriendsService]
})
@View({
    template: `
   <p>My name: {{ myName }}</p>
   <ul>
    <li *ng-for="#name of names">
    {{ name }}
    </li>
   </ul>
  `,
    directives: [NgFor]
})
class DisplayComponent {
    myName:string;
    names: Array<string>;

    constructor(friendsService: FriendsService) {
        this.myName = 'Alice';
        this.names = friendsService.names;
    }
}

bootstrap(DisplayComponent);

 

posted @ 2015-08-18 03:39  Zhentiw  阅读(301)  评论(0)    收藏  举报