是否可以通过NGXS存储对用户进行路由解析?
我进行了这样的测试,但我不知道这是否是正确的方法:
import {ActivatedRouteSnapshot, Resolve} from "@angular/router";
import {Todo} from "./todos.models";
import {Observable} from "rxjs/Observable";
import {Select, Store} from "@ngxs/store";
import {GetTodo, TodosState} from "./todos.state";
import {Injectable} from "@angular/core";
@Injectable()
export class TodoResolver implements Resolve<Todo> {
constructor(
private store:Store
) {}
@Select(TodosState.getTodo)
private todo$:Observable<Todo>;
resolve(route:ActivatedRouteSnapshot): Observable<Todo>
{
const id = <number><any> route.paramMap.get('id');
this.store.dispatch(new GetTodo(id));
return this.todo$;
}
}
当我尝试此操作时,应用程序将挂起。没有显示错误。
欢迎所有帮助。 谢谢
答案 0 :(得分:3)
请忽略,我自己找到了解决方案...
将代码更改为:
@Injectable()
export class TodoResolver implements Resolve<Todo> {
constructor(
private store:Store
) {}
resolve(route:ActivatedRouteSnapshot): Observable<Todo>
{
const id = <number><any> route.paramMap.get('id');
this.store.dispatch(new GetTodo(id));
return this.store.selectOnce(TodosState.getTodo);
}
}
答案 1 :(得分:1)
我认为rauwebieten的解决方案仅适用于同步操作。 selectOnce执行后,异步操作将修改存储。
我必须设置两个状态来处理异步操作。一个是托多斯州,另一个是请求托多州。
代码如下:
@Injectable()
export class AsyncTodoResolver implements Resolve<Todo> {
@Select(RequestingTodoState)
private todo$:Observable<Todo>;
constructor(
private store:Store
) {}
resolve(route:ActivatedRouteSnapshot): Observable<Todo> {
const id = <number><any> route.paramMap.get('id');
return this.store.dispatch(new GiveOrFetchTodo(id))
.pipe(
withLatestFrom(todo$),
map([any, todo]) => {return todo;}
);
}
}