Angular、store-select 与 http get
Angular, store-select with http get
我想守护一条路线并执行以下操作:
- 检查用户是否在 ngrx-store
- 如果用户在店内 return canActivate 为真
- 如果没有进行 http-get 并接收用户
- 如果用户回来,将其存储在商店中,并且 return 在 canActivate
上为真
- if 401, return false
这是我目前得到的:
@Injectable({providedIn: 'root'})
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router, private store: Store<AppState>) {
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
return this.store.select(selectUser).pipe(
take(1),
map(user => {
if (!!user) {
return true;
}
return this.authService.getUser$()
.pipe(
map(user => {
this.store.dispatch(addUser({user: user}));
return true;
})
)
})
);
}
}
错误:
Type 'Observable<true | Observable<boolean>>' is not assignable to type 'boolean | UrlTree | Observable<boolean | UrlTree> | Promise<boolean | UrlTree>'.
问题是 return this.authService... return 是一个 Observable,它导致
可观察<可观察>.
如何解开这个心结?
if (!!user) {
return true; // Returns a boolean - OK
}
return this.authService.getUser$()
.pipe(
map(user => {
this.store.dispatch(addUser({user: user}));
return true; // Returns an observable of a boolean - Not OK
})
)
替换为 switchMap :
return this.store.select(selectUser).pipe(
first(),
switchMap(user => {
if (!!user) {
return of(true);
}
return this.authService.getUser$()
.pipe(
map(user => {
this.store.dispatch(addUser({user: user}));
return true;
})
)
})
);
我想守护一条路线并执行以下操作:
- 检查用户是否在 ngrx-store
- 如果用户在店内 return canActivate 为真
- 如果没有进行 http-get 并接收用户
- 如果用户回来,将其存储在商店中,并且 return 在 canActivate 上为真
- if 401, return false
这是我目前得到的:
@Injectable({providedIn: 'root'})
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router, private store: Store<AppState>) {
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
return this.store.select(selectUser).pipe(
take(1),
map(user => {
if (!!user) {
return true;
}
return this.authService.getUser$()
.pipe(
map(user => {
this.store.dispatch(addUser({user: user}));
return true;
})
)
})
);
}
}
错误:
Type 'Observable<true | Observable<boolean>>' is not assignable to type 'boolean | UrlTree | Observable<boolean | UrlTree> | Promise<boolean | UrlTree>'.
问题是 return this.authService... return 是一个 Observable,它导致 可观察<可观察>.
如何解开这个心结?
if (!!user) {
return true; // Returns a boolean - OK
}
return this.authService.getUser$()
.pipe(
map(user => {
this.store.dispatch(addUser({user: user}));
return true; // Returns an observable of a boolean - Not OK
})
)
替换为 switchMap :
return this.store.select(selectUser).pipe(
first(),
switchMap(user => {
if (!!user) {
return of(true);
}
return this.authService.getUser$()
.pipe(
map(user => {
this.store.dispatch(addUser({user: user}));
return true;
})
)
})
);