I was wondering what the best approach is to load data in Angular 5. Of course, we want to keep components dumb ;) For now, I am using a resolver and Angular calls the resolver in a specific route. Basically, data is loaded before a component has been initialised so I can show a loader animation to the user.
eg.
AResolver.resolver.ts
@Injectable()
export class AResolver implements Resolve<any> {
constructor(private readonly aService: AService) {}
resolve(route: ActivatedRouteSnapshot) {
return this.aService.find(route.paramMap.get('id'));
}
}
M.module.ts
export const MRoutes: Routes = [
{
path: 'route-x',
component: AComponent,
resolve: AResolver
}
];
AComponent.component.ts
@Component({
selector: 'a-super-fancy-name',
})
export class AComponent {
constructor(private readonly route: ActivatedRoute) {}
}
Well, so far so good, but:
- What if I have resolvers with dependencies? So, to resolve B we need an id from A? Should I use a resolver wrapper? Thus I do something like:
Example
@Injectable()
export class ABResolver implements Resolve<any> {
constructor(private readonly aService: AService, private readonly bService: BService) {}
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
return this.aService.resolve(route, state).map((result) => this.bService.resolveWithId(result.Id));
}
}
I guess this is the best approach because we still have 2 independent resolvers that can be reused. In general, is it a good practice to make resolver wrappers for all components that need data or only for resolvers that depend on other resolvers, or shouldn't I use resolver wrappers at all?
-
What about other methods in a resolver (like the
resolveWithId
)? -
in
AResolver
route.paramMap is used the get the id. Isn't it better to pass the id because this looks tightly coupled? -
What are the alternatives?
-
What are the drawbacks of the approach I use?
from Angular 2+ - data loading: best practices
No comments:
Post a Comment