首页 > 解决方案 > 已解决在后端创建用户后重定向问题

问题描述

我执行此方法是为了将用户保存在form-registrar-usuario.component 中

  registrarUsuario(){
    const role = this.route.snapshot.params["role"]
    if(role == "Proponedor"){
      this.autorizacionService.registrarUsuario(
        role,
        this.valoresForm.value.username,
        this.valoresForm.value.email,
        this.valoresForm.value.password,
        this.valoresForm.value.password2,
        "",
        "",
        "",
        "" 
        ).subscribe(
          response => {
            console.log("me voy al mainprop");
            this.router.navigate(["/mainprop/"]);
          },
          error=>{
            console.log(error);
            this.errorentrada=error;
          });
    }

  }

它从AutorizacionService调用 registrarUsuario

  registrarUsuario(role:string, username:string, email: string, password:string, password2:string, first_name:string, last_name:string, second_last_name:string, phone_number:string){
    //todo

    return this.http.post(
      environment.apiURL.concat('registrarusuario/'),
      {role, username, email, password, password2, first_name, last_name, second_last_name, phone_number}
    ).pipe(
      tap(response=>this.setSession(response)),
      shareReplay()
    );
  
  }  

在 AutorizacionService 方法中,我调用 setSession 来保存令牌和用户

  private setSession(authResult){
    let token = authResult.token;
    let payload = <JWTPayload> jwt_decode(token);
    const expiresAt = moment.unix(payload.exp);
    localStorage.setItem('token', authResult.token);
    localStorage.setItem('expires_at', JSON.stringify(expiresAt.valueOf()));
    localStorage.setItem('user', authResult.user);
    //this.usuarioService.obtenUsuario(payload.user_id).subscribe((usuarioRetornado:Usuario) => localStorage.setItem('user', JSON.stringify(usuarioRetornado)) );
  }

我可以将用户保存在数据库中,但第一种方法永远不会重定向到 mainprop。 应用路由模块

  { path: "mainprop", component: PrincipalProponedorDeSubrutinasComponent, canActivate:[SesionIniciada, EsUsuarioProponedorDeSubrutinas]},

这些是 SessionIniciada 和 EsUsuarioProponedorDeSubrutinas

@Injectable({
  providedIn: 'root'
})
export class EsUsuarioProponedorDeSubrutinas implements CanActivate{
  constructor(
    private autorizacionService: AutorizacionService,
    ) { }
    canActivate(): boolean {
      return this.autorizacionService.obtenUsuarioSesion()["role"]=="Proponedor";
    }

}


@Injectable({
  providedIn: 'root'
})
export class SesionIniciada implements CanActivate{
  constructor(
    private autorizacionService: AutorizacionService,
    ) { }
    canActivate(): boolean {
      return this.autorizacionService.isLoggedIn();
    }

}

问题是从canActivate调用的obtenUsuarioSesion无法从localStorage中获取用户,在while循环中无限停留。但是我想之前就存储了来自 localStorage 的用户。

  obtenUsuarioSesion():Usuario{
    //localStorage.clear();
    //return null;
    console.log("entro al bucle");
    while(localStorage.getItem('user')=="undefined"){}
    console.log("salgo del bucle: ", localStorage.getItem('user'));
    return JSON.parse(localStorage.getItem('user'));
  }

提前致谢

解决了:

问题是“registrarusuario/”附加的方法没有返回用户,所以不能本地存储在setSession中,取到obtenUsuarioSession中

标签: angulartypescript

解决方案


如果 localStorage 中不存在密钥,则 localStorage.getItem() 将返回 null(来源:https ://developer.mozilla.org/en-US/docs/Web/API/Storage/getItem )

在您的情况下,代码会卡在 while 上,因为如果与 localStorage 键 'user' 关联的值等于 'undefined' 字符串,则条件为真

您可以尝试将条件更改为:

while(localStorage.getItem('user') === null){}

虽然我不认为有while循环是必要的,因为理论上当守卫运行时localStorage应该已经包含用户


推荐阅读