为什么使用重定向提交表单不起作用?

Why form submit with redirect doesn't work?

提问人:Edoardo 提问时间:11/17/2023 最后编辑:Tony NgoEdoardo 更新时间:11/21/2023 访问量:55

问:

我在 angular 16 中有这段代码:

<div class="position-absolute top-50 start-50 translate-middle">
<div class="text-center">
    <img id="logo" src="/assets/images/logo.jpg">
</div>
<div>
<form (submit)="login(username.value, password.value)">
    <div class="mb-3">
      <label for="exampleInputEmail1" class="form-label">Username</label>
      <input type="text" class="form-control" id="exampleInputEmail1" #username>
    </div>
    <div class="mb-3">
      <label for="exampleInputPassword1" class="form-label">Password</label>
      <input type="password" class="form-control" id="exampleInputPassword1" #password>
    </div>
    
    <input style="background-color: #007b32; border-color: #007b32;" type="submit" class="btn btn-primary" value="Accedi" >
</form>
</div>
login(username: string, password: string){
this.auth.login(username, password).subscribe({
  next: (response: any) =>{
    if(response["token"]){
      sessionStorage.setItem("Authorization", response["token"])
    }
    this.router.navigateByUrl("/index")
  },
  error: (msg) => {
    console.log(msg)
    
  }
});}

路由

const routes: Routes = [
      { path: "", redirectTo: "/index", pathMatch: "full" },
      { path: "login", component: LoginComponent, pathMatch: "prefix" },
      {
        path: "index",
        component: IndexComponent,
        canActivate: [IsAuthFilter],
        pathMatch: "prefix",
      },
      { path: "**", redirectTo: "/index", pathMatch: "full" },
    ];

现在,我的问题是,如果我使用输入类型 submit 并以这种方式调用方法 login(),则表单不会在 /index 上重定向,而是在同一页面上重定向。 此外,在调试中,它会重定向到“/index/”,但后来它会返回登录页面。

我不明白为什么。 我过去使用一个简单的按钮缓解了这个问题,但我不喜欢这种方式,我想使用表单。

也许我没有以正确的方式使用它?!

谢谢

角度 angularjs angular16

评论

1赞 Tony Ngo 11/20/2023
你也可以分享你的路由配置吗?
0赞 Edoardo 11/21/2023
当然: const routes: Routes = [ {path:'', redirectTo:'/index', pathMatch: 'full'}, {path:'login', component:LoginComponent, pathMatch: 'prefix'}, {path: 'index', component:IndexComponent, canActivate: [IsAuthFilter], pathMatch: 'prefix'}, {path: '**', redirectTo: '/index', pathMatch: 'full'} ];
0赞 akop 11/21/2023
我会说,你说并将你重定向回登录页面。AuthGuardfalse
0赞 Edoardo 11/21/2023
但是为什么?我正在单击按钮上设置令牌
0赞 Eliseo 11/21/2023
检查你的防护装置,并检查 response[“token”] 是否为空或未定义

答: 暂无答案