官术网_书友最值得收藏!

Overriding at runtime

There is a way to decide what to inject for/into a construct at runtime. So far, we have been very explicit about when to override, but we can do this with a bit of logic added to it by using the useFactory keyword. It works like the following:

let factory = () => {
if(condition) {
return new FakeService();
} else {
return new Service();
}
}

@Component({
providers : [
{ provide : Service, useFactory : factory }
]
})

This factory can in itself have dependencies; we specify those dependencies with the deps keyword like so:

let factory = (auth:AuthService, logger: Logger) => {
if(condition) {
return new FakeService();
} else {
return new Service();
}
}

@Component({
providers : [
{ provide : Service, useFactory : factory,
deps: [AuthService, Logger] }
]
})

Here, we highlighted the condition variable, which is a Boolean. There can be a ton of reasons why we would want to be able to switch the implementation. One good case is when the endpoint don't exist yet and we want to ensure it calls our FakeService instead. Another reason could be that we are in testing mode and by just changing this one variable we can make all our services rely on a fake version of themselves.

主站蜘蛛池模板: 和田县| 怀仁县| 明星| 蓝山县| 永嘉县| 鄂托克旗| 察哈| 双柏县| 集贤县| 克山县| 焉耆| 霞浦县| 东辽县| 上林县| 育儿| 清河县| 杭州市| 鄂州市| 德令哈市| 巴彦县| 泊头市| 嘉善县| 嘉鱼县| 永寿县| 富顺县| 定兴县| 陵水| 灵台县| 诸暨市| 项城市| 延长县| 龙海市| 什邡市| 齐河县| 西峡县| 乃东县| 资中县| 梅河口市| 吉木萨尔县| 桦南县| 阜新市|