Leveraging Dependency Injection to reduce duplicated code in Angular #135
Replies: 4 comments 5 replies
-
Thanks for putting it all together. It was indded a good read! |
Beta Was this translation helpful? Give feedback.
-
You make a good point on factories simplifying testing. BUT...why not use @Injectable to create a single service that holds all these pure function factories rather than injecting providers as factories? Having to manage injection tokens like you suggest implies a possible need to have multiple instances of these factories - the use doesn't align well with the stated premiss of the article. |
Beta Was this translation helpful? Give feedback.
-
Nice article, thank you for sharing! I think by using some inheritance we can reduce amount of boilerplate even more. E.g. this could be generic part (it could support more configuration options, like all you do you your factory functions, but this is just an example): @Injectable({
providedIn: 'root',
})
export abstract class RouteObservable extends Observable<string> {
protected abstract bag: 'params' | 'queryParams';
protected abstract property: string;
constructor(route: ActivatedRoute) {
super(subscriber => {
const subscription = route[this.bag].pipe(pluck(this.property)).subscribe(subscriber);
return () => {
subscription.unsubscribe();
};
});
}
} And here is specific value extractor: @Injectable({providedIn: 'root'})
export class IdQueryParam extends RouteObservable {
protected bag = 'queryParams' as const;
protected property = 'id';
} Finally, this is how you use it in your component: constructor(id$: IdQueryParam) {
id$.pipe(takeUntil(this.destroyed$)).subscribe(console.log);
} So, the most repetitive part is also the shortest (basically moving providers from And in your tests it could be as simple as this: providers: [
{
provide: IdQueryParam,
useValue: scheduled(of('1234'), asyncScheduler),
},
], |
Beta Was this translation helpful? Give feedback.
-
This is really good stuff |
Beta Was this translation helpful? Give feedback.
-
How to eliminate duplicated code when getting route params, query params or data from Activated Route in Angular by using dependency injection. Read the article here.
Beta Was this translation helpful? Give feedback.
All reactions