套路之前 1.providers 是一个提供者 2. 把提供者放到容器中 3, 其他人使用这个提供者
提供者有什么类型呢?
service
repository
factory
helper
使用套路
@Injectable()
export class TestService{
create(){
return '我就是providers create'
}
}
注册到moduels
@Moules({
provides([TestService])
})
使用
@Controller()
export class helloController{
constructor(private service:TestService){
}
@Get('/测试提供者')
test测试提供者(){
return this.service.create()
}
}
你会觉得奇怪
constructor(private helloService:HelloService){
}
this.helloService 就有了数据 为什么呢
我们应该的做法是
class AAAA{
helloService:HelloService
constructor(helloService:HelloService){
this.helloService=helloService;
}
}
---
constructor(private helloService:HelloService){
}的语法糖最后就是变成
class AAAA{
helloService:HelloService
constructor(helloService:HelloService){
this.helloService=helloService;
}
}
可以猜测 在nest新建AAAA的时候,会找到constructor的参数
最后var aaa=new AAAA(new HelloService());
自己定义providers
nest提供了多个自己定义providers的方法
useValue
在我看来他就是把 aaaaclass当做 bbbclass 使用
class aaaaclassService(){
constroller(){
log("aaaaclassService 被初始化中")
}
}
@Modules({
provide:aaaaclassService
useValue:bbbclassService
})
以后你使用 bbbclassService 就会用 aaaaclassService来代替
这个功能有什么用
猜测在测试的时候 realclassService 使用 mockservice 代替
前提是 realclassService mockservice的结构需要一直
方法一样多,一样多?
测试吧
class realclassService{
say(){
log("我是realclassService")
}
}
class mockservice{
say(){
log("我是mockservice")
}
}
@Modules({
providers([
{
provide:realclassService,
useValue:mockservice()
}
])
})
//contoller 测试 realclassService 看是不是使用 mockservice 的方法了
@controller('test')
classs testController{
constructor(private realclassService:realclassService){}
@Get("/testrealservice")
test(){
this.realclassService.say()
}
}
果然成功了
我们在测试下 useValue是单例模式吗
class mockservice{
+ constuctor(){
+ log("我是mockservice 初始化,看看是不是 useValue是单例模式吗")
+ }
say(){
log("我是mockservice")
}
}
测试结果也是 单例
非类提供者
上面我们使用的是一个class name作为标记 我们现在使用 字符串作为标记 能注入吗?
@Modules({
providers:[{
providers:'我就是一个providers字符串',
useValue:{say(){log(你好我是你的say function )}}
}]
})
@Controller直接使用
@Controller("/test"){
constructor(private 我就是一个providers字符串:我是一个接口){}
@get("/我测试下privder是string")
我测试下privder是string(){
this.我就是一个providers字符串.say();
}
}
我们需要定义一个接口
interface 我是一个接口{
say:()=>{}
}
而且在contructor上面也需要做手脚
@Controller("/test"){
+ constructor(private @Inject('我就是一个providers字符串') testService:我是一个接口){}
@get("/我测试下privder是string")
我测试下privder是string(){
this.testService.say();
}
}