美文网首页
三、Providers

三、Providers

作者: Nick_4438 | 来源:发表于2022-10-25 09:03 被阅读0次

    说明

    Providers 在nest内是服务或者功能的提供则,nest内很多类都通过privider实现,如service, repository, factory, helper,通过构造函数注入,使用@Injectable()装饰器注释类

    使用

    简单使用

    • user.service.ts
    import { Injectable } from '@nestjs/common';
    import { CreateUserDto } from './dto/create-user.dto';
    import { UpdateUserDto } from './dto/update-user.dto';
    
    @Injectable()   //添加装饰器
    export class UserService {
      create(createUserDto: CreateUserDto) {
        return 'This action adds a new user';
      }
    
      findAll() {
        return `This action returns all user`;
      }
    
      findOne(id: number) {
        return `This action returns a #${id} user`;
      }
    
      update(id: number, updateUserDto: UpdateUserDto) {
        return `This action updates a #${id} user`;
      }
    
      remove(id: number) {
        return `This action removes a #${id} user`;
      }
    }
    
    
    • 定义user module,user.module.ts
    import { Module } from '@nestjs/common';
    import { UserService } from './user.service';
    import { UserController } from './user.controller';
    
    @Module({
      controllers: [UserController],
      providers: [
                  UserService,
                  { provide: "test",useClass: UserService},
                  {provide: "ds",useValue: ['TB', 'PDD', 'JD']} //自定义注入值
                ],
      exports: [UserService,{ provide: "test",useClass: UserService}, 
      {provide: "ds",useValue: ['TB', 'PDD', 'JD']}]    //如果想暴露给其他服务使用
    })
    export class UserModule {}
    
    
    • app.module.ts引入模组
    import { Module } from '@nestjs/common';
    import { AppController } from './app.controller';
    import { AppService } from './app.service';
    import { UserModule } from './user/user.module';
    
    @Module({
      imports: [UserModule],
      controllers: [AppController],
      providers: [AppService],
    })
    export class AppModule {}
    
    
    
    • app.controller.ts使用service
    import { Controller, Get,Inject } from '@nestjs/common';
    import { AppService } from './app.service';
    import { UserService } from './user/user.service';
    
    @Controller()
    export class AppController {
      constructor(private readonly appService: AppService,
          private readonly userService: UserService,
          @Inject("test") private readonly service1: UserService,
          @Inject("ds") private list1:string[] ) {}
    
      @Get()
      getHello(): string {
        return this.appService.getHello();
      }
      @Get('findAll')
      findAllUsers(): string{
        return this.userService.findAll()+' [app]';
      }
      @Get('findOne')
      findOne(): string{
        return this.service1.findOne(1)+' [app]';
      }
      
      @Get('list')
      list(): string[]{
        return this.list1;
      }
      
    }
    
    

    其他

    如果服务 之间有相互的依赖 或者逻辑处理 可以使用 useFactory

    import { Module } from '@nestjs/common';
    import { UserService } from './user.service';
    import { UserService2 } from './user.service2';
    import { UserService3 } from './user.service3';
    import { UserController } from './user.controller';
     
    @Module({
      controllers: [UserController],
      providers: [{
        provide: "Xiaoman",
        useClass: UserService
      }, {
        provide: "JD",
        useValue: ['TB', 'PDD', 'JD']
      },
        UserService2,
      {
        provide: "Test",
        inject: [UserService2],
        useFactory(UserService2: UserService2) {
          return new UserService3(UserService2)
        }
      }
      ]
    })
    export class UserModule { }
    
    • 注入代码如下:
    constructor(@Inject('Test') private readonly Test: any)
    
    • 异步模式,useFactory 返回一个promise 或者其他异步操作
    import { Module } from '@nestjs/common';
    import { UserService } from './user.service';
    import { UserService2 } from './user.service2';
    import { UserService3 } from './user.service3';
    import { UserController } from './user.controller';
     
    @Module({
      controllers: [UserController],
      providers: [{
        provide: "Xiaoman",
        useClass: UserService
      }, {
        provide: "JD",
        useValue: ['TB', 'PDD', 'JD']
      },
        UserService2,
      {
        provide: "Test",
        inject: [UserService2],
        useFactory(UserService2: UserService2) {
          return new UserService3(UserService2)
        }
      },
      {
        provide: "sync",
        async useFactory() {
          return await  new Promise((r) => {
            setTimeout(() => {
              r('sync')
            }, 3000)
          })
        }
      }
      ]
    })
    export class UserModule { }    
    

    相关文章

      网友评论

          本文标题:三、Providers

          本文链接:https://www.haomeiwen.com/subject/crngzrtx.html