buc*_*aci 5 redux ngrx angular ngrx-store
我目前有一个容器(有状态)组件,它根据方法中的路由参数(id)调度一个select和一个get动作ngOnInit。这些操作的要点是在我的商店中拥有数据和选定的 id。
我很好奇在解析器中分派这些动作是否正确?
感谢您的回复。
我的组件:
@Component({
selector: 'app-container',
templateUrl: './container.component.html',
styleUrls: ['./container.component.css']
})
export class ContainerComponent implements OnInit, OnDestroy {
private componetDestroyed$ = new Subject();
constructor(private store: Store<fromRoot.State>, private route: ActivatedRoute) { }
ngOnInit() {
this.route.params
.filter(params => params['id'])
.map(params => params['id'])
.takeUntil(this.componetDestroyed$)
.subscribe(id => {
this.store.dispatch(new GetAction(id));
this.store.dispatch(new SelectAction(id));
});
}
ngOnDestroy() {
this.componetDestroyed$.next();
this.componetDestroyed$.unsubscribe();
}
}
Run Code Online (Sandbox Code Playgroud)
我的路线:
[{
path: ':id',
component: ContainerComponent
}]
Run Code Online (Sandbox Code Playgroud)
解析器将是:
@Injectable()
class MyResolver implements Resolve<any> {
constructor(private store: Store<fromRoot.State>) {}
resolve(route: ActivatedRouteSnapshot, state: RouteStateSnapshot) {
let id = route.params['id'];
this.store.dispatch(new SelectAction(id));
this.store.dispatch(new GetAction(id));
return null;
}
Run Code Online (Sandbox Code Playgroud)
以及修改后的路线:
[{
path: ':id',
component: ContainerComponent,
resolve: {
store: MyResolver
}
}]
Run Code Online (Sandbox Code Playgroud)
这就是为什么我不确定这是否正确,因为商店将永远是null。
ngOnInit基于 的方式调度操作的方式没有任何问题this.route.params。
重要的是解析器是路由的数据提供者。如果您不提供数据,那么您就错误地使用了它们。
在你的情况下,它听起来更像是一个canActivate负责发出动作并允许路线的警卫。
不过,您可以扩展解析器来选择您想要的数据。
@Injectable({
providedIn: 'root',
})
export class DataResolver implements Resolve<number> {
constructor(private store: Store) {
}
public resolve(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<any> {
this.store.dispatch(LoadDataForMyRoute());
return this.store.pipe(
select(dataForMyRoute),
filter(data => !!data), // <- waiting until data is present
take(1), // <- important to add
);
}
}
Run Code Online (Sandbox Code Playgroud)
在您的组件中,您可以像这样访问它而不是this.store.select.
constructor(
protected readonly store: Store,
protected readonly activatedRoute: ActivatedRoute,
) {}
public ngOnInit(): void {
this.activatedRoute.data.subscribe(data => {
// everything is here.
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1668 次 |
| 最近记录: |