angular依赖提供者

依赖提供者

前面我们简单介绍了依赖注入的用法,通过providers注入一个类,这样的方式被称为类提供者。其实,也可以提供一个替代类、一个对象或一个工厂函数作为提供者。(原文阅读)

类提供者

正如我们前面的介绍,演示的就是类提供者的创建和使用

// comment.service.ts
import { Injectable } from '@angular/core';
import comments from '../data/comments';
@Injectable()
export class CommentService {
  constructor() { }
  getComments() {
    return comments;
  }
}
providers: [CommentService]

上面类提供者的语法实际上是一种简写形式,它会扩展成一个由 Provider接口定义的提供者配置对象。

展开写法是这样的:

providers: [{ provide: CommentService, useClass: CommentService }]

Provider接口定义是一个具有两个属性的对象字面量:

  1. provide属性存有令牌(如上面provide: CommentServiceCommentService),它作为一个 key,在定位依赖值和配置注入器时使用;

  2. 第二个属性是一个提供者定义对象,它告诉注入器要如何创建依赖值。 提供者定义对象中的 key可以是 useClass, 也可以是 useExistinguseValueuseFactory。(后面介绍)

提供不同于令牌(provide)的类

我们再创建一个first-comment服务来获取第一条评论:

// first-comment.service.ts
import { Injectable } from '@angular/core';
import comments from '../data/comments';

@Injectable()
export class FirstCommentService {
  constructor() { }
  getComments() {
    return comments[0];
  }
}

provideuseClass的值不一样也是可以的:

// service.component.ts
@Component({
  // ...
  providers: [ {provide: CommentService, useClass: FirstCommentService}]
})
export class ServiceComponent implements OnInit {
  constructor(private commentService: CommentService) { 
    // 能够获取到我们想要的第一条评论数据
    console.log(this.commentService.getComments());
  }
  // ...
}

别名提供者

useExisting指向的服务一定是已经注册过的,这是和useClass的区别之一

// service.component.ts

@Component({
  // ...
  providers: [
    FirstCommentService,
    // 如果用useClass, 则会得到两份FirstCommentService实例
    { provide: CommentService, useExisting: FirstCommentService }
  ]
})

值提供者

对于很简单的值,没必要把它做成一个类,可用useValue提供简单的值

// service.component.ts
@Component({
  // ...
  providers: [{provide: CommentService, useValue: 'aaaa'}]
})
export class ServiceComponent implements OnInit {
  constructor(private commentService: CommentService) { 
    console.log(this.commentService); // 'aaaa'
  }
 // ...
}

上面可以是一个字符串,当然也可以是一个对象了~

非类令牌

上面每个provide都是一个类,那么也可以用其它数据类型作为令牌

// service.component.ts
@Component({
  // ...
  providers: [{ provide: 'HttpApi', useValue: 'http://abc.com/'}]
})

/** 这种,注入构造函数的方式就有变化了 **/
export class ServiceComponent implements OnInit {
  constructor(@Inject('HttpApi') readonly httpApi) { 
    console.log(this.httpApi); // http://abc.com/
  }
 // ...
}

使用InjectionToken对象

每当你要注入的类型无法确定时,例如在注入接口、可调用类型、数组或参数化类型时,都应使用InjectionToken

一般情况下无法使用ts接口作为令牌,但又想要限制值的类型,可以借助InjectionToken

// comment.ts
import { InjectionToken } from "@angular/core";
// 定义接口
export interface CommentT {
  postId: number;
  id: number;
  name: string;
  email: string;
  body: string;
}
// 导出 括号里面的参数是该令牌的一个描述,可选
export const CommentType = new InjectionToken<Comment>('comment type');
// service.component.ts
@Component({
  // ...
  providers: [{ provide: CommentType, useValue: {id: '0001', name: 'Jack', body: 'BBBB'}}]
})

export class ServiceComponent implements OnInit {
  constructor(@Inject(CommentType) private commentType: CommentT) { 
    this.name = this.commentType.name;
  }
 // ...
}

工厂提供者

工厂提供者用来自定义实例化服务

我们先修改下CommentService:

// comment.service.ts
...
@Injectable()
export class CommentService {
  constructor(private comment: CommentT[]) { }
  getComments() {
    return this.comment;
  }
}

再创建一个根据评论id查询的服务get-comment-by-index.service

// get-comment-by-index.service.ts
import { Injectable } from '@angular/core';
import comments from '../data/comments';
@Injectable()
export class GetCommentByIndexService {
  constructor() {}
  getCommentsByIndex(index = 0) {
    if (index > comments.length || index < 0) {
      return comments;
    } else { 
      return comments.slice(index, index + 1);
    }
  }
}

使用工厂提供者,注入GetCommentByIndexService

// service.component.ts
@Component({
  // ...
  providers: [
    { 
      provide: CommentService,
      useFactory(getCommentByIndexService: GetCommentByIndexService) {
        return new CommentService(getCommentByIndexService.getCommentsByIndex(1));
      },
      deps:[GetCommentByIndexService]
    }
  ]
})

export class ServiceComponent implements OnInit {
  constructor(private commentService: CommentService, ) { 
    // 能够得到第二条评论数据
    console.log(this.commentService.getComments());
  }
 // ...
}

useFactory是一个方法,处理你想要的逻辑并返回。如果有依赖其他的服务,应当在deps中注册。

总结

  1. 令牌与提供者类名一致时,可简写(推荐);

  2. 使用useValue来提供一个简单值;

  3. 如果要限制注入的数据类型,使用InjectionToken对象;

  4. 工厂提供者可自定义更丰富的服务,如果有依赖其他的服务,应当在deps中注册。

欢迎关注我的公众号,公众号将第一时间更新angular教程:
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yanyi24

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值