• Angular中创建对象的两种方式:
    • 通过new手动创建一个对象实例出来,let car = new Car();
    • 通过依赖注入的方式,注入对象的实例,通过声明依赖注入,不需要new关键字创建实例
  • Angular认为组件是与用户操作有关的东西,与用户操作无关的内容都应该剥离出去放在服务对象当中;服务对象从外部为组件提供服务(例如:日志、记时、后台服务的访问)

    1、日志服务依赖案例

    1.1、创建日志服务

  • 在目录下创建服务类LogService

    • @Injectable({providedIn: 'root'})表示当前服务是可被注入的,指定提供者是root ```typescript //Injectable装饰器修饰说明当前服务可被注入 @Injectable({ //指定当前服务对象由根模块中提供 providedIn: “root” }) export class LogService{

    doLog(action: any){ //模拟获取当前用户 let user = {name: ‘jack’, role: ‘admin’}; let time = new Date().toLocaleString(); console.log(角色:${user.role} 用户名:${user.name} 操作:${action} 时间:${time}) } } ```

    1.2、在组件中注入服务

  • 在组件的constructor(log:LogService)构造函数中声明所需的依赖,Angular在类创建的时候就会提供所需的服务,服务是单例的 ```typescript @Component({ selector: ‘app-test-component’, templateUrl: ‘./test-component.component.html’, styleUrls: [‘./test-component.component.css’] }) export class TestComponentComponent { //LogService类型的变量log log: LogService;

    //在构造函数中指定变量的类型,声明依赖 constructor(log: LogService) { this.log = log; }

    addThing(){ //直接使用依赖的LogService this.log.doLog(“adding”); }

    removeThing(){ this.log.doLog(“removing”); }

}

  1. <a name="tf2AD"></a>
  2. ## 1.3、界面效果
  3. ```html
  4. <h1>货物管理</h1>
  5. <button (click)="addThing()">添加</button>
  6. <button (click)="removeThing()">删除</button>
  • 点击按钮后查看控制台日志结果,观察LogService被成功注入提供

image.png

2、非单例服务声明

  • 要声明非单例的服务提供者,组件级别的服务提供者,对于一些有属性的服务,多个组件同时使用一个服务,会导致属性值冲突,此时就需要使用非单例的服务,每一个组件维护自己的属性
  • 组件级别的服务提供这只能在当前组件中作用

    1. //Injectable装饰器修饰说明当前服务可被注入
    2. //同时不指定服务提供者为root
    3. @Injectable()
    4. export class LogService{
    5. doLog(action: any){
    6. //模拟获取当前用户
    7. let user = {name: 'jack', role: 'admin'};
    8. let time = new Date().toLocaleString();
    9. console.log(`角色:${user.role} 用户名:${user.name} 操作:${action} 时间:${time}`)
    10. }
    11. }
  • 在组件中使用providers中声明当前服务的服务提供者

    1. @Component({
    2. selector: 'app-ng-for-component',
    3. templateUrl: './ng-for-component.component.html',
    4. styleUrls: ['./ng-for-component.component.css'],
    5. providers: [LogService] //声明组件级别的服务提供这,此服务只在当前组件中生效,避免数据冲突
    6. })
    7. export class NgForComponentComponent {
    8. count: number = 5;
    9. log: LogService;
    10. constructor(log: LogService) {
    11. this.log = log;
    12. }
    13. doAdd(){
    14. this.log.doLog("adding!");
    15. }
    16. }