#Dependency Injection

19 messages · Page 1 of 1 (latest)

tardy rapids
#

Hello I am creating a injectable service and passing data from the parent component to the injectable service via @Inject & (specifying the useValue within the parent's providers), this works but I want to be able to pass the components class variables. Would this be possible?

sly lotus
#

It's better if you post some code.

stuck plume
#

g!codeblock @tardy rapids

glad irisBOT
#

@tardy rapids, you can use the following snippet to have your code formatted and colored by Discord. Replace ts with the language you need (i.e. html, js, css, etc)
```ts
// your code goes here
```

tardy rapids
#

within parent component providers: [ { provide: 'data', useValue: 123, }, CustomService ] constructor of parent: readonly data: CustomService, CustomService: ```@Injectable({providedIn: 'root'})
export class CustomService {

constructor(@Inject('data') private data: number) {
this.data = data;
}

}``` 123 is stored within is a class variable within the parent.. but i cant reference it

stuck plume
#

Don't provide: a string ('data'). Use an InjectionToken
And generally you use:

@Injectable({ providedIn: 'root' }) // Always 'root' unless you _know_ better!
export class CustomService {}

Then you don't need to put CustomService in providers: [list]

#

And I have no idea why you want to inject 'data' anyway...

sly lotus
#

So, you want to inject in a component, a service constructed with a parameter passed by the component itself?

tardy rapids
#

correct

#

i want to use data within the parent component into the injected component

sly lotus
#

The injected component or service?

tardy rapids
#

the injected component is the service (CustomService)

sly lotus
#

If it's a service it's not a component.

tardy rapids
#

injected service, my bad

sly lotus
#

I doubt it's possible, considering that injecting a dependency in a component suppose that deps to be already instantiated.

#

Why do you want to pass that value in constructor?

#

Sound like a design issue here.

tardy rapids
#

the service needs to grab default values, (which are initialized in the parent component)

sly lotus
#

Instead of using these values in service's constructor, send them to it through a method from the component and, if as I think they have to be consumed by other components, expose them through a Subject.