Optional
用于构造函数参数的参数装饰器,将参数标记为可选依赖项。如果找不到依赖项,则 DI 框架提供 null。
Parameter 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.
参见
说明
可以与其他修改依赖注入方式的参数装饰器一起使用。
Can be used together with other parameter decorators that modify how dependency injection operates.
Further information available in the Usage Notes...
使用说明
以下代码允许结果为空的可能性:
The following code allows the possibility of a null
result:
class Engine {}
@Injectable()
class Car {
constructor(@Optional() public engine: Engine) {}
}
const injector =
Injector.create({providers: [{provide: Car, deps: [[new Optional(), Engine]]}]});
expect(injector.get(Car).engine).toBeNull();