1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

Angular InjectionToken throws 'No provider for InjectionToken'

Discussão em 'Angular' iniciado por Paradoxis, Setembro 29, 2024.

  1. Paradoxis

    Paradoxis Guest

    I'm currently learning the new Angular framework, and I'm trying to make a dynamic search bar which accepts a service name as an argument in order for it to dynamically resolve a service to query the backend service with.

    For this I'm using an Injector, and loading the the service during ngOnInit. This works fine when using a string based provider, however my IDE notes that it's deprecated and I should use an InjectionToken which I can't seem to wrap my head around.

    I expected the following code to work, as removing all instances of InjectionToken and replacing them with the direct string literal works:

    I tried looking at the following documentation, but I didn't quite understand it as I feel like I did exactly what it says, yet it keeps telling me it doesn't work: https://angular.io/guide/dependency-injection-providers

    Could someone tell me what I'm doing wrong?
    Thanks

    Module declaration

    // app.module.ts
    @NgModule({
    declarations: [
    AppComponent,
    SearchBarComponent
    ],
    imports: [
    BrowserModule,
    HttpClientModule,
    AppRoutingModule
    ],
    providers: [
    {
    provide: new InjectionToken<ISearchable>('CustomerService'), // <-- doesn't work; 'CustomerService' <-- works
    useValue: CustomerService
    }
    ],
    bootstrap: [AppComponent]
    })
    export class AppModule { }


    Search bar component:

    // search-bar.component.ts
    @Component({
    selector: 'search-bar',
    templateUrl: './search-bar.component.html',
    styleUrls: ['./search-bar.component.sass']
    })
    export class SearchBarComponent implements OnInit {

    @Input()
    source: string;

    private searcher: ISearchable;

    constructor(private injector: Injector) {}

    ngOnInit() {
    // error: Error: No provider for InjectionToken CustomerService!
    let token = new InjectionToken<ISearchable>(this.source);
    this.searcher = this.injector.get<ISearchable>(token);

    // this works, but it's deprecated and will probably break in the future
    // this.searcher = this.injector.get(this.source);
    console.log(this.searcher);
    }
    }


    Using the search bar:

    <!-- app.component.html -->
    <div class="row justify-content-center mb-2">
    <div class="col-8">
    <search-bar title="Customers" source="CustomerService"></search-bar>
    </div>
    </div>


    Edit: Here's an example with the error:

    https://stackblitz.com/edit/angular-3admbe

    Continue reading...

Compartilhe esta Página