Guy*_*uyT 9 angular angular-router angular-resolver
我想知道在Angular 5中加载数据的最佳方法是什么.当然,我们希望保持组件哑;;现在,我正在使用一个解析器,Angular在特定路径中调用解析器.基本上,数据在组件初始化之前加载,因此我可以向用户显示加载器动画.
例如.
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'));
}
}
Run Code Online (Sandbox Code Playgroud)
M.module.ts
export const MRoutes: Routes = [
{
path: 'route-x',
component: AComponent,
resolve: AResolver
}
];
Run Code Online (Sandbox Code Playgroud)
AComponent.component.ts
@Component({
selector: 'a-super-fancy-name',
})
export class AComponent {
constructor(private readonly route: ActivatedRoute) {}
}
Run Code Online (Sandbox Code Playgroud)
好吧,到目前为止一切顺利,但是:
例
@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));
}
}
Run Code Online (Sandbox Code Playgroud)
我想这是最好的方法,因为我们仍然有2个可以重复使用的独立解析器.通常,为所有需要数据的组件或仅依赖于其他解析器的解析器制作解析器包装器是一个好习惯,还是不应该使用解析器包装器?
解析器中的其他方法怎么样(比如resolveWithId
)?
在AResolver
route.paramMap中使用获取id.传递id是不是更好,因为这看起来紧密耦合?
有哪些替代方案?
我使用的方法有哪些缺点?
解析器在纸面上很好,但只有当你可以轻松地从当前路由获取所有参数时,不幸的是这种情况很少发生,有时你必须访问父路由,有时你不想将所有信息存储在路由参数中,有时您不想阻止导航,而且路由器参数也不是非常灵活的功能,它可能很容易使重构复杂化(您不能简单地更改父路由参数而不影响子解析器,并且编译器无法检查错误)。
角度没有任何预定义/推荐的方式来加载数据。根据应用程序规模,您可以根据需要简单地在每个组件中加载数据,或者施加某些规则或通用接口/抽象类,或者使用 rxjs 等缓存共享服务。基本上,您只能在自定义架构和类似 Redux 的 ngrx 方法之间进行选择。ngrx 显然提出了一些限制和限制,并提供了结构和总体方向。
归档时间: |
|
查看次数: |
591 次 |
最近记录: |