Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DI constructor with optional parameters

Tags:

My constructor has optional parameters and they seem to mess with the predominant way of doing DI.

constructor(public name:string, public age?:number, private _service:Service); 

Typescript understandably doesn't like that I put a non optional parameter behind an optional one, furthermore the service doesn't get injected when the optional parameter isn't set. How do I solve that? I can't put it somewhere else in the constructor since I would be expected setting the service manually.

Is there something like field injection?

@Inject() private _service:Service;  constructor(public name:string, public age?:number); 

Should I replace the optional parameters with default values? Any other suggestions?

EDIT: As discussed below, I tried to inject a service into an object that isn't created by Angular's DI. This doesn't work. Since I can't create this class (model) using DI I now pass the service manually from the class that instantiates this objects.

like image 651
KenavR Avatar asked Apr 06 '16 09:04

KenavR


People also ask

Which decorator is used to indicate that the DI is optional?

OptionallinkParameter decorator to be used on constructor parameters, which marks the parameter as being an optional dependency. The DI framework provides null if the dependency is not found.

How do you pass optional parameters in typescript?

In Typescript, making optional parameters is done by appending the “?” at the end of the parameter name in the function when declaring the parameters and the parameters which are not marked with “?” i.e not optional parameter are called as default parameters or normal parameters where it is must and compulsory to pass ...

What is constructor DI?

Dependency injection (DI) is a process whereby objects define their dependencies, that is, the other objects they work with, only through constructor arguments, arguments to a factory method, or properties that are set on the object instance after it is constructed or returned from a factory method.

What is the use of optional parameter?

A method that contains optional parameters does not force to pass arguments at calling time. It means we call method without passing the arguments. The optional parameter contains a default value in function definition. If we do not pass optional argument value at calling time, the default value is used.


1 Answers

Just add the @Optional() decorator before the constructor parameter that should only be injected if there was a provider registered.

import { Optional } from '@angular/core';      constructor(public name:string, @Optional() public age:number) 
like image 189
Günter Zöchbauer Avatar answered Oct 30 '22 17:10

Günter Zöchbauer