zl程序教程

您现在的位置是:首页 >  前端

当前栏目

[Angular 2] 4. Inject service into component

Angular Service Component INTO Inject
2023-09-14 09:00:55 时间

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);