#Dependency Injection
19 messages · Page 1 of 1 (latest)
It's better if you post some code.
g!codeblock @tardy rapids
@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
```
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
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...
So, you want to inject in a component, a service constructed with a parameter passed by the component itself?
The injected component or service?
the injected component is the service (CustomService)
If it's a service it's not a component.
injected service, my bad
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.
the service needs to grab default values, (which are initialized in the parent component)
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.