简体   繁体   中英

How can we use forwardRef in a angular service to avoid Circular dependency?

I have gone through couple of articles about resolving circular dependency in angular, all are mentioning about using forwardRef to resolve circular dependency. All the reference that I found online are only dealing with component service interaction.

My scenario is something like:

If two service depends on each other and which is causing the class circular dependency issue. I can't find a proper thread related to using forwardRef or any best way to resolve circular dependency between two services.

If anyone have faced any such similar issues and have an advice on how to approach towards this issue is appreciable.

I know circular dependency is avoidable but if we need to do it in a proper way, then what approach should I go with?

Thanks

I have gone through couple of articles about resolving circular dependency in angular, all are mentioning about using forwardRef to resolve circular dependency.

They shouldn't be telling you that because that's not what it's for.

forwordRef lets you reference an injectable token before it has been provided .

Circular dependencies is not an Angular problem. It is a TypeScript compiling problem.

If two service depends on each other and which is causing the class circular dependency issue

The imports are circular. It has nothing to do with the classes , but when you try have file A import file B, and B also imports A then you have a circular problem.

I know circular dependency is avoidable but if we need to do it in a proper way, then what approach should I go with?

This sounds like service A depends upon service B, and service B depends upon service A.

If the circular imports are a result of trying to use the Angular injector, then you can fix the issue by using interfaces instead. At least one of your services should have an interface, and then you define an injection token for that service.

import { InjectionToken } from '@angular/core';
export interface IServiceB {}

export const SERVER_B: InjectionToken<IServiceB> = new InjectionToken<IServiceB>('SERVICE_B');

You can then implement IServiceB in the ServiceB class, but it's very important not to define the IServiceB interface in the same file as ServiceB otherwise everything is for not.

You can then provide this token in the module.

@NgModule({
   ...
   providers: [
       { provide: SERVICE_B: useClass: ServiceB }
   ]
)

Now you can safely inject this service into ServiceA

@Injectable()
export class ServiceA {
    constructor(@Inject(SERVICE_B) serviceB: IServiceB) {...}
}

No circular imports now.

To go the other direction you might have to define another interface for ServiceA .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM