Vetouz
Vetouz

Reputation: 159

how to share service in angular

I have an angular application with different module. Module are lazy loaded. Let's say in module A I have a service userService that I want to use in a component in module B, let's say library.component. So I have this code :

A.module.ts :

@NgModule({
  declarations: [...],
  imports: [...],
  providers: [UserService]
})
export class UserModule { }

And in library.component.ts I have this import import {UserService} from ...

The structure of my directory is as follow :

--moduleA
  --service
    --user.service.ts
  A.module.ts
--moduleB
  --component
    --library.component.ts

What I want to know is, knwowing that modules A and B are lazy loaded is it a bad practice to import a service from A in B ?

Should I instead move the functions of userService that I use in a service in module B or maybe define a shared module.

Thanks in advance for your response.

Upvotes: 1

Views: 59

Answers (2)

Gvs Akhil
Gvs Akhil

Reputation: 2581

This is a scenario where it depends on the individuals framing their architecture and I would go in this way:

Point1: I would use the way you used when I dont have a lot of methods its because when we look at the closures when we access a service it creates a prototype of all the methods thats available and thats doesnot matter anyway if you have only some 3 - 4 methods

Closures in my service

Point2: If we have 100's of methods and calling that service in our module only for a single method is not recommended and I would prefer to go for shared module in this scenario.

This totally depends on the architecture you design :)

Upvotes: 1

whitefang
whitefang

Reputation: 1081

One of the solution for your question is that

@Injectable({ providedIn: 'root' })

After adding this to service, this service can be called in the other services constructor constructor(private service: Service) { }

It was explained at https://angular.io/guide/dependency-injection

Upvotes: 0

Related Questions