Angular router.navigateByUrl does not change site content

Discussão em 'Angular' iniciado por Karo S-S, Outubro 7, 2024.

  1. Karo S-S

    Karo S-S Guest

    I am working on client application using newest angular (18). I tried to make the site that after login it redirects to tasks. But when I do navigate, it changes URL and site stays on login page, when I refresh it loads tasks correctly. I tried searching about it here on stack, on github and on reddit. Nothing helped me. Please keep in mind I do not have a lot experience in angular, just did one project where I had charts on single site to display on TV in real time.

    My routes

    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}
    ];


    Task Component

    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))
    }))
    }
    }


    login Component

    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')
    }
    }


    I tried making new project to see if maybe I messed up some config, but it was the same. I have routing declared in app.config,

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


    as per new version this is the way. But I tried making my own router module like in previous versions and it did not work either.

    Continue reading...

Compartilhe esta Página