- Architecting Angular Applications with Redux,RxJS,and NgRx
- Christoffer Noring
- 222字
- 2021-08-27 19:56:16
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.