【问题标题】:Angular guard is not triggering routing角度防护没有触发路由
【发布时间】:2020-12-12 12:35:33
【问题描述】:

我正在从输入中获取值

onSubmit(form: NgForm) {
   this.sessionService.get(form.value.login, form.value.password);
 }

然后将它们与 db 值进行比较,看看它们是否正确。然后我正在更新商店

get(login, password) {
    this.http.get<Auth>(url)
      .pipe(take(1), tap(data => {
        if (data.accounts.elisa.email === login || data.accounts.elisa.login === login && data.accounts.elisa.password === password) {
          this.sessionStore.update({isAuth: true});
        } 
      })).subscribe();
  }

并将isAuth 发送到CanActivate 守卫

canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> {
    return this.sessionQuery.getStoreData$;
  }

主要问题是如果值正确,我可以登录,但只能在第二次单击提交按钮时登录。首次单击并将 isAuth 值设置为 true 后,商店正在正确更新

getStoreData$ 实现

export class SessionQuery extends Query<SessionState> {
  getStoreData$ = this.select(store => store.isAuth);

  constructor(protected store: SessionStore) {
    super(store);
  }
}

并存储配置

import { Injectable } from '@angular/core';
import { Store, StoreConfig } from '@datorama/akita';

export interface SessionState {
   isAuth: boolean;
}

export function createInitialState(): SessionState {
  return {
    isAuth: false
  };
}

@Injectable({ providedIn: 'root' })
@StoreConfig({ name: 'session' })
export class SessionStore extends Store<SessionState> {

  constructor() {
    super(createInitialState());
  }
}

【问题讨论】:

  • getStoreData的实现是什么
  • @PetrusNguyễnTháiHọc 更新问题
  • The main problem is that I can login if the values is correct, but only on second click on submit button. The store is updating correctly after first click and setting isAuth value to true -> 在第一次点击提交按钮时,它会尝试将商店设置为登录。但它是异步的,需要时间。您可能会立即将用户重定向到另一条路线,例如home,并且由于防护尚未更新,您认为登录在第一次点击时不起作用。要修复它,您应该重定向回调。 (PS:你没有包含你的重定向代码,所以这只是一个猜测。)

标签: angular authentication rxjs store auth-guard


【解决方案1】:

我已经找到了解决办法,希望能帮助遇到同样问题的人=)

canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> {
    return this.sessionQuery.getStoreData$.pipe(first(value => value === true));
  }

【讨论】:

    【解决方案2】:

    像这样尝试super(createInitialState())

    function createInitialState(): SessionState { ... }
    
    @Injectable({ providedIn: 'root' })
    @StoreConfig({ name: 'session' })
    export class SessionStore extends Store<SessionState> {
      constructor() {
        super(createInitialState());
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-04-22
      • 2020-12-01
      • 2021-05-17
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      • 2013-09-12
      • 2020-12-28
      • 2016-02-27
      相关资源
      最近更新 更多