Angular router.navigateByUrl 不会更改网站内容

问题描述 投票:0回答:2

我正在使用最新的角度(18)开发客户端应用程序。我试图让网站在登录后重定向到任务。但是当我导航时,它会更改 URL 并且站点保留在登录页面上,当我刷新时它会正确加载任务。我尝试在 stack、github 和 reddit 上搜索它。没有任何帮助我。请记住,我在角度方面没有太多经验,只是做了一个项目,我在单个站点上有图表可以实时显示在电视上。

我的路线

import { Routes } from '@angular/router'
import { LoginComponent } from './login/login.component';
import { RegisterComponent } from './register/register.component';
import { TaskComponent } from './task/task.component';

export const routes: Routes = [
    {path: 'tasks', component:TaskComponent},
    {path: 'register', component:RegisterComponent},
    {path: 'login', component: LoginComponent},
    {path: '**', component: LoginComponent}
];

任务组件

import { Component, Injectable } from '@angular/core';
import { MatSlideToggle } from '@angular/material/slide-toggle';
import { MatRadioModule } from '@angular/material/radio';
import { ApiService } from '../api.service';
import { MatIconModule } from '@angular/material/icon'
import { ExcelImport } from '../../models/ExcelImport';
import { NgFor, NgIf, DatePipe } from '@angular/common';
import { MatCardModule } from '@angular/material/card'
import { Router } from '@angular/router';
import { AppModule } from '../app.module';

@Component({
  selector: 'app-task',
  standalone: true,
  imports: [AppModule,MatCardModule,DatePipe,NgIf,NgFor,MatSlideToggle, MatRadioModule, MatIconModule],
  templateUrl: './task.component.html',
  styleUrl: './task.component.css'
})@Injectable()
export class TaskComponent {
  constructor(private service:ApiService, private router:Router){}
  items!:ExcelImport[];
  fileName = '';
  ngOnInit()
  {
    this.items = [];
    this.service.getTasksForUser().subscribe(res => res.forEach(element => {
      this.items.push(new ExcelImport(element.project, element.type, element.workerName, element.workerCompany, element.day))
  }))
  }
}

登录组件

import { Component, Injectable, OnDestroy, OnInit } from '@angular/core';
import { Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { FormBuilder } from '@angular/forms';
import { ReactiveFormsModule } from '@angular/forms';
import { ApiService } from '../api.service';
import { jwtDecode } from 'jwt-decode';
import { LayoutComponent } from '../layout/layout.component';
import { MatCardModule } from '@angular/material/card';
import { MatInputModule } from '@angular/material/input';
import { AppModule } from '../app.module';
import { webSocket } from 'rxjs/webSocket';
import { SnackBarService } from '../service/snackbar.service';

@Component({
  selector: 'app-login',
  standalone: true,
  imports: [AppModule, ReactiveFormsModule, MatCardModule, MatInputModule],
  templateUrl: './login.component.html',
  styleUrl: './login.component.css'
})
@Injectable()
export class LoginComponent {
  
  loginForm = this.fb.group({
    email: ['', Validators.required],
    password: ['',Validators.required]
  });

  url:string = 'ws://localhost:5160/RFID/ConnectClientToWebSocket';
  wsSubject = webSocket({
    url: this.url,
    deserializer: ({data}) => data
  });
  constructor(private fb:FormBuilder, 
    private authComponent:ApiService,
    private router:Router,
    private layout:LayoutComponent,
  private snackbar:SnackBarService) 
  {        
  }
  
  ngOnInit(){
    this.wsSubject.subscribe((message) =>
      {
        if(message === "Connected!" || message === "Already connected!")
          console.log(message)
        else if(message === "Nieznaleziono pracownika!")
        {
          this.snackbar.ShowSnackBar(message);
        }
        else
        {
          this.userLogin(message.replace('"', ''));
        }
      })}
  userLogin(token:string)
  {
    this.wsSubject.complete();
    this.wsSubject.unsubscribe();
    const decodedToken: any = jwtDecode(token.toString());
    this.layout.UserName = decodedToken.unique_name
    localStorage.setItem("UserId", decodedToken.TagId)
    localStorage.setItem("Token", token);
    this.router.navigateByUrl("/tasks").then(() => console.log('navigated'))
  }
  login(){
    const val = this.loginForm.value
    if (val.email && val.password)
    {
      this.authComponent.login(val.email, val.password).subscribe(x => 
      {
        if(x == null)
          this.router.navigateByUrl("/login");
        else
        {
          this.userLogin(x.toString())
        }
      }) 
    }
  }
  logout()
  {
    localStorage.removeItem("UserId")
    localStorage.removeItem("Token")
    this.layout.UserName = '';
    this.router.navigateByUrl('/login')
  }
}

我尝试创建新项目,看看我是否弄乱了一些配置,但结果是一样的。我在 app.config 中声明了路由,

export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(routes),
    provideClientHydration(),
    provideAnimationsAsync(),
    provideHttpClient(withInterceptors([AuthInterceptor])),
  ],
};

根据新版本,就是这样。但我尝试像以前的版本一样制作自己的路由器模块,但它也不起作用。

angular angular-routing
2个回答
0
投票

确保您已将

baseHref
添加到
index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>My app</title>
    <meta charset="UTF-8" />
    <base href="/">
  </head>
  <body>
    <app-root>Loading...</app-root>
  </body>
</html>

0
投票

websocket 可能有问题,但你可以尝试 this.router.navigate(["login"])

© www.soinside.com 2019 - 2024. All rights reserved.