Angular 2+ - 数据加载:最佳实践

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)

好吧,到目前为止一切顺利,但是:

  1. 如果我有依赖的解析器怎么办?那么,要解决B我们需要一个来自A的id?我应该使用旋转变压器包装吗?因此,我做了类似的事情:

@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个可以重复使用的独立解析器.通常,为所有需要数据的组件或仅依赖于其他解析器的解析器制作解析器包装器是一个好习惯,还是不应该使用解析器包装器?

  1. 解析器中的其他方法怎么样(比如resolveWithId)?

  2. AResolverroute.paramMap中使用获取id.传递id是不是更好,因为这看起来紧密耦合?

  3. 有哪些替代方案?

  4. 我使用的方法有哪些缺点?

kem*_*sky 0

解析器在纸面上很好,但只有当你可以轻松地从当前路由获取所有参数时,不幸的是这种情况很少发生,有时你必须访问父路由,有时你不想将所有信息存储在路由参数中,有时您不想阻止导航,而且路由器参数也不是非常灵活的功能,它可能很容易使重构复杂化(您不能简单地更改父路由参数而不影响子解析器,并且编译器无法检查错误)。

角度没有任何预定义/推荐的方式来加载数据。根据应用程序规模,您可以根据需要简单地在每个组件中加载数据,或者施加某些规则或通用接口/抽象类,或者使用 rxjs 等缓存共享服务。基本上,您只能在自定义架构和类似 Redux 的 ngrx 方法之间进行选择。ngrx 显然提出了一些限制和限制,并提供了结构和总体方向。