首页 > 解决方案 > Angular: Difference in runtime with Providers in AppModule and providedIn: 'root'?

问题描述

We are currently searching a way to use decorators in our REST services to simplify the process, and I've found a solution after regrouping a lot of research. However, there is still a small issue.

With a @API() class decorator using mixins, we are able to inject services and extend our REST Service to get the same base injected services, to set the baseAPI and so on...

Use Case 1

@Injectable()
@API({ useExternalSources: true })
export class VehicleService extends APIProperties { }

@NgModule({
  ...
  providers: [
    VehicleService
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

enter image description here

Use Case 2: However, when it comes to use these services without specifying the providers but using @Injectable({ providedIn: 'root' }), it fails to recognize the injected services and app breaks.

@Injectable({ providedIn: 'root' })
@API({ useExternalSources: true })
export class VehicleService extends APIProperties { }

@NgModule({
  ...
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

enter image description here

Question: Why app breaks when using providedIn: 'root' instead of specifying services in AppModule providers ?

Here is a link to the project to Github, so you can clone it and reproduce. Master branch uses Use Case 1, and the branch with-provided-in uses Use Case 2


Moreover, even if it is working, we still have a warning since Angular v12:
DEPRECATED: DI is instantiating a token "" that inherits its @Injectable decorator but does not provide one itself. This will become an error in a future version of Angular. Please add @Injectable() to the "" class.
-> In a class decorator, it seems quite difficult to add this @Injectable

Thank you in advance and have a nice day!

标签: angulartypescriptdecorator

解决方案


推荐阅读