import {Component} from 'angular2/core'; import {User} from "./User"; import {UserService} from "./user-service"; import {Logger} from "./logger-service"; @Component({ selector: 'appTest',template: ` <ul> <li *ngFor="#user of users"><span>{{user.name}}</span>{{user.age}}</li> </ul> `,providers: [ Logger,UserService ] }) export class App { users: User[]; constructor(private userService: UserService) { this.users = userService.getUsers(); } }
/** * Created by dell on 2016/9/8. */ import {Injectable} from 'angular2/core'; import {Users} from "./user-data"; import {Logger} from "./logger-service"; @Injectable() export class UserService { constructor(private logger: Logger) { } getUsers() { this.logger.log('get users'); return Users; } }
/** * Created by dell on 2016/9/9. */ import {Injectable} from 'angular2/core'; @Injectable() export class Logger{ logs: string[] = []; log(msg) { this.logs.push(msg); console.warn('From logger class: ' + msg); } }原文链接:https://www.f2er.com/angularjs/148886.html