typescript Angular 15 -考虑使用@Inject装饰器来指定注入令牌

dgsult0t  于 2022-12-19  发布在  TypeScript
关注(0)|答案(2)|浏览(272)

在使用angular的工厂提供程序并在factory.service.ts中发送两个参数之后,我想显示“factory”和一个布尔值。
它似乎在其他Angular 版本中工作得很好,但在Angular 15版本中出现了一个问题。
我不知道问题出在哪...
home.component.ts

import { Component, Inject, OnInit } from '@angular/core';
import { FactoryService } from '../factory.service';
import { LogService } from '../log.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
  providers: [LogService, 
   {provide: 'another', useClass: LogService}, 
   {provide: 'same',useExisting: LogService}, 
   {provide: 'githubUrl',useValue: 'https://github.com/abcd'}, 
   {provide: 'factory',useFactory: (logService) => {
              return new FactoryService(logService, true);},
              deps: [FactoryService]
   }]
})

export class HomeComponent implements OnInit{

    constructor(private log:LogService, 
        @Inject('another') private another, 
        @Inject('same') private same,
        @Inject('githubUrl') private url,
        @Inject('factory') private factory         
        ) {
        console.log("this.log === this.another", this.log === this.another)
        console.log("this.log === this.same", this.log === this.same)
        console.log(this.url)
    }

    ngOnInit(): void {
        this.log.info('logservice');
        this.factory.log();
    }

}

factory.service.ts

import { Inject, Injectable } from "@angular/core";
import { LogService } from "./log.service";

@Injectable()
export class FactoryService {
    constructor(private logService: LogService, private isFactory: boolean) {}

    public log() {
        this.logService.info(`factory ${this.isFactory}`);
    }
}

错误

Error: src/app/factory.service.ts:6:57 - error NG2003: No suitable injection token for parameter 'isFactory' of class 'FactoryService'.
  Consider using the @Inject decorator to specify an injection token.

6     constructor(private logService: LogService, private isFactory: boolean) {}
                                                          ~~~~~~~~~

  src/app/factory.service.ts:6:68
    6     constructor(private logService: LogService, private isFactory: boolean) {}
                                                                         ~~~~~~~
    This type is not supported as injection token.

我看过官方文件,但我不知道问题出在哪里。

hwamh0ep

hwamh0ep1#

根据错误消息的建议,您应该为自定义参数使用@Inject装饰器,否则Angular会将其视为依赖项并尝试解决它。
由于您没有这样的isFactory提供程序,Angular 抛出错误。
添加名为isFactory的@Inject装饰器

工厂.服务.ts

......
    constructor(private logService: LogService, @Inject('isFactory') private isFactory: boolean) {}
......

提供isFactory值并删除new FactoryService中的第二个参数

主组件ts

......
  providers: [LogService, 
   {provide: 'another', useClass: LogService}, 
   {provide: 'same',useExisting: LogService}, 
   {provide: 'githubUrl',useValue: 'https://github.com/abcd'}, 
   {
      provide: 'isFactory',
      useValue: true,
   },
   {provide: 'factory',useFactory: (logService) => {
              return new FactoryService(logService);},
              deps: [FactoryService]
   },
]
})

未测试代码。
有关详细信息,请参阅https://www.positronx.io/how-to-pass-parameters-to-angular-service-using-inject/

jogvjijk

jogvjijk2#

最简单的解决方法是使用注入令牌。如果使用factory,则这些令牌是树可摇动的。

const IS_FACTORY = new InjectionToken<boolean>('Is factory', {
  providedIn: 'root', // optional
  factory: () => true
});

为了提供,

providers: [{ provide: IS_FACTORY, useValue: false}],

如果您想在具有类型安全的组件中使用

const isFactory = inject(IS_FACTORY); // or the @Inject method

inject的第二个参数允许使用optional、self、host等常用分辨率修饰符。

相关问题