Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 角度页面被重定向到主页面_Angular - Fatal编程技术网

Angular 角度页面被重定向到主页面

Angular 角度页面被重定向到主页面,angular,Angular,我在Angular routing中定义了多个路由,并输入了重置密码url,但它会自动导航到登录页面 const routes: Routes = [ { path: "", component: DashboardComponent, pathMatch: "full", canActivate: [AuthGuardService], }, { path: "reset-password&q

我在Angular routing中定义了多个路由,并输入了重置密码url,但它会自动导航到登录页面

const routes: Routes = [
  {
    path: "",
    component: DashboardComponent,
    pathMatch: "full",
    canActivate: [AuthGuardService],
  },
  {
    path: "reset-password",
    component: ResetPasswordComponent,
    pathMatch: "full",
  },
  {
    path: "dashboard",
    component: DashboardComponent,
    pathMatch: "full",
    canActivate: [AuthGuardService],
  },
  {
    path: "auth",
    data: { preload: true },
    loadChildren: () =>
      import("./authentication/authentication.module").then(
        (x) => x.AuthenticationModule
      ),
  },
  {
    path: "not-authorized",
    pathMatch: "full",
    canActivate: [AuthGuardService],
    component: NotAuthorizedComponent,
  },
  { path: "**", component: NotFoundComponent },
];

@NgModule({
  imports: [
    RouterModule.forRoot(routes, {
      preloadingStrategy: CustomPreloadingService,
      initialNavigation: "enabled",
    }),
  ],
  exports: [RouterModule],
  providers: [RouterExtService],
})
export class AppRoutingModule {}
应用了Auth-Guard服务,该服务检查令牌是否存在于本地存储中。如果令牌不存在,它将用户重定向到另一个模块中的/Auth/login页面

但在重置密码时,我甚至没有添加AuthGuard来检查此设置,而是在打开页面直接url时”http://localhost:4200/reset-密码”,然后自动导航到登录页面

这是AuthModule

const authRoutes: Routes = [{ path: "login", component: LoginComponent }];
@NgModule({
  declarations: [LoginComponent, ForgotPasswordComponent],
  imports: [SharedModule, RouterModule.forChild(authRoutes)],
  entryComponents: [ForgotPasswordComponent],
})
export class AuthenticationModule {}
这是登录组件

errors: AllValidationErrors[] = []
  
  constructor(
    private router: Router,
    private authService: AuthServiceService,
    private loader: LoaderService,
    private fb: FormBuilder,
    private toaste: CustomToastrService,
    private modalService: NzModalService,
  ) {}

  LogInForm = this.fb.group({
    userName: ['', Validators.required],
    userPassword: ['', Validators.required],
  })

  ngOnInit() {
    if (this.authService.isLoggedIn()) {
      this.router.navigate(['/'])
    }
  }

  onSubmit() {
    this.credentialMissing = false
    this.blocckedByAdmin = false
    this.errors = []
    if (this.LogInForm.valid) {
      this.loader.Show(this.div)
      let credentials: any = this.LogInForm.value
      this.authService
        .login(credentials.userName, credentials.userPassword)
        .subscribe(
          (api) => {
            if (api.success) {
              var apiResponse = api.response
              //Case 1 : User is InActive
              if (apiResponse && apiResponse.inActive == true) {
                this.loader.Hide(this.div)
                this.LogInForm.reset()
                this.blocckedByAdmin = true
              } else {
                //CASE 2 : User is Active but OTP not required
                if (
                  apiResponse &&
                  (apiResponse.inActive == null ||
                    apiResponse.inActive == false) &&
                  apiResponse.twoFactorAuthType == ''
                ) {
                  this.loader.Hide(this.div)
                  let detail = {
                    rights: api.response.authRights,
                    committees: api.response.authCommitees,
                  }
                  this.authService.setUserDetail(detail)
                  this.authService.setToken(api.response.token).then(() => {
                    this.router.navigateByUrl('')
                  })
                } else {
                  // Case 3 : User is Active Confirm OTP
                  if (
                    apiResponse.otpBasedUserId != null &&
                    apiResponse.otpBasedUserId > 0
                  ) {
                    this.loader.Hide(this.div)
                    this.toaste.Success(api.message)
                    this.ValidateOTPModel(apiResponse.otpBasedUserId)
                  } else {
                    this.toaste.Error('Problem in sending OTP ,try again')
                  }
                }
              }
            } else {
              this.loader.Hide(this.div)
              this.LogInForm.reset()
              this.credentialMissing = true
            }
          },
          (error) => {
            this.loader.Hide(this.div)
            this.credentialMissing = true
            this.LogInForm.reset()
          },
        )
    } else {
      this.errors = getFormValidationErrors(this.LogInForm)
    }
  }
这是重置密码组件

@Component({
  selector: "app-reset-password",
  templateUrl: "./reset-password.component.html",
  styleUrls: ["./reset-password.component.scss"],
})
export class ResetPasswordComponent implements OnInit {
  constructor(
    private activeRoute: ActivatedRoute,
    private formBuider: FormBuilder,
    private userService: UserService,
    private router: Router,
    private toaster: CustomToastrService
  ) {}

  resetEmail: string = "";
  resetDate: string = "";
  div: string = "data-div";
  errors: AllValidationErrors[] = [];
  passwordValues: IResetPassword;
  ngOnInit() {
    this.resetEmail = this.activeRoute.snapshot.queryParams["email"];
    this.resetDate = this.activeRoute.snapshot.queryParams["dt"];
    this.resetPasswordForm.patchValue({
      email: this.resetEmail,
      dateEncrypted: this.resetDate,
    });
  }

  resetPasswordForm = this.formBuider.group({
    confirmPassword: ["", [Validators.required]],
    newPassword: ["", [Validators.required]],
    email: [""],
    dateEncrypted: [""],
  });

  ResetPassword() {
    this.errors = [];
    this.passwordValues = this.resetPasswordForm.value;
    if (this.resetPasswordForm.valid) {
      if (this.passwordValues.email == "") {
        this.errors.push({
          error: "",
          keyError: "Email",
          key: "required ",
        });
      }
      if (this.passwordValues.dateEncrypted == "") {
        this.errors.push({
          error: "",
          keyError: "Date ",
          key: "required ",
        });
      }
      this.errors = [];
      if (
        this.passwordValues.confirmPassword != this.passwordValues.newPassword
      ) {
        this.errors.push({
          error: "",
          keyError: "Not Similar To Confirm Password",
          key: "New Password ",
        });
      } else {
        this.userService
          .ResetPasswordViaLink(this.passwordValues)
          .subscribe((pwd) => {
            if (pwd && pwd.success) {
              this.router.navigateByUrl("/auth/login");
            } else {
              this.toaster.Error(pwd.message);
            }
          });
      }
    } else {
      this.errors = getFormValidationErrors(this.resetPasswordForm);
    }
  }

  ResetForm() {}
}

您可以尝试删除路径匹配:“full”吗。 在我的项目中,我使用它时没有使用pathMatch,它可以正常工作

  {
    path: "reset-password",
    component: ResetPasswordComponent
  },

是的,我尝试过,但也没有通过删除路径匹配来工作:“full”也可以共享登录组件映射。是的。我编辑我的帖子,这样你也可以看到登录和身份验证模块。请共享ResetPasswordComponent代码ResetPasswordComponent也添加在编辑中。将帮助您调试路由