Javascript 为路由提供异步依赖项';s Angular 2中的通用组件。路线';s解析等价
我想提供一组通用组件,这样他们就不会知道提供依赖关系的服务。这些组件的依赖关系是承诺。 换句话说,我希望将实例数据访问排除在这些通用组件的范围之外。任何依赖项,尤其是要呈现的数据和组件配置,都应该由声明组件的上下文提供给组件。 当我将视图中的组件声明为DOM标记时,这很容易,例如:Javascript 为路由提供异步依赖项';s Angular 2中的通用组件。路线';s解析等价,javascript,routing,components,angular,Javascript,Routing,Components,Angular,我想提供一组通用组件,这样他们就不会知道提供依赖关系的服务。这些组件的依赖关系是承诺。 换句话说,我希望将实例数据访问排除在这些通用组件的范围之外。任何依赖项,尤其是要呈现的数据和组件配置,都应该由声明组件的上下文提供给组件。 当我将视图中的组件声明为DOM标记时,这很容易,例如: 但是当组件直接被路由调用时,我如何处理呢? 我读过,但这个问题的答案肯定让我不满意。接受答案建议,将依赖项放入组件,但这意味着失去组件的通用方式。 在Angular 1中,这样做的方法是使用路由声明的resolve
但是当组件直接被路由调用时,我如何处理呢?
我读过,但这个问题的答案肯定让我不满意。接受答案建议,将依赖项放入组件,但这意味着失去组件的通用方式。
在Angular 1中,这样做的方法是使用路由声明的resolve
属性。Angular的1分辨率在Angular 2中的等效值是多少?
请参考示例,因为它非常准确。我遇到了完全相同的问题
Route的专用组件(将容纳泛型组件)可能是解决方案。但这并不优雅,它是一种绕过而非解决方案 RC 4中的角2引入了路由属性 此属性是具有实现Resolve接口的属性的对象 每个解析器必须是且具有返回可观察| Promise | any的方法解析 当您将ActivatedRoute作为
route
注入组件时,您可以从route.snapshod.data['someResolveKey']访问每个已解析的属性
angular.io文档中的示例:
class Backend {
fetchTeam(id: string) {
return 'someTeam';
}
}
@Injectable()
class TeamResolver implements Resolve<Team> {
constructor(private backend: Backend) {}
resolve(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<any>|Promise<any>|any {
return this.backend.fetchTeam(route.params.id);
}
}
@NgModule({
imports: [
RouterModule.forRoot([
{
path: 'team/:id',
component: TeamCmp,
resolve: {
team: TeamResolver
}
}
])
],
providers: [TeamResolver]
})
class AppModule {}
您可以在组件中获取数据:
export class SomeComponent implements OnInit {
resource : string;
team : string;
constructor(private route: ActivatedRoute) {
}
ngOnInit() {
this.team = this.route.snapshot.data['team'];
// UPDATE: ngOnInit will be fired once,
// even If you use same component for different routes.
// If You want to rebind data when You change route
// You should not use snapshot but subscribe on
// this.route.data or this.route.params eg.:
this.route.params.subscribe((params: Params) => this.resource = params['resource']);
this.route.data.subscribe((data: any) => this.team = data['team']);
}
}
希望有帮助,
快乐的黑客
export class SomeComponent implements OnInit {
resource : string;
team : string;
constructor(private route: ActivatedRoute) {
}
ngOnInit() {
this.team = this.route.snapshot.data['team'];
// UPDATE: ngOnInit will be fired once,
// even If you use same component for different routes.
// If You want to rebind data when You change route
// You should not use snapshot but subscribe on
// this.route.data or this.route.params eg.:
this.route.params.subscribe((params: Params) => this.resource = params['resource']);
this.route.data.subscribe((data: any) => this.team = data['team']);
}
}