angularangular-routingangular-routerangular-routerlink

Angular Routing problems with Refresh


here: https://stackblitz.com/edit/planificador?file=src/app/partehoras/components/detail/detail.component.html

The first route loaded is this one

first route loaded

in app.module I have this

app.module

in partehoras.module I have this

partehoras.module

When I click here

click name

I go to this route

new route

But When I refresh this page I go to this one again

afterrefresh

Any idea, please?

Thanks


Solution

  • The main problem is in the main.component.ts:

    @Component(...)
    export class MainComponent implements OnInit {
      ...
    
      ngOnInit(): void {
         ...;
    
         this.sharedDataService
          .getEmpleado(this.empleadoID)
          .pipe()
          .subscribe(data => {
              
              this.nombreEmpleado = data.nombre;
    
              console.log('Empleado', this.nombreEmpleado);
    
              this.router.navigate(['/partehoras', this.empleadoID]); // Problem here!
            },
            err => console.log(err),
            () => {})
      }
    }
    

    Now, why is this line a problem?

    Angular starts loading the components in your application and resolving their routes. One of these components is the MainComponent and it's ngOnInit method you have:

    this.router.navigate(['/partehoras', this.empleadoID]);
    

    This means that once the subscribe emits information, you will perform a redirect if this component is appearing in the screen.

    Since this component contains the DetailComponent via the <router-outlet></router-outlet> this means when you want to load the DetailComponent you must always pass by it first.

    Under normal navigation this is not a problem, but when we refresh, we trigger the ngOnInit method, which prevents us from ever reaching the DetailComponent.

    There is no simply resolution to this. The problem is you are performing a redirect in the ngOnInit method, which is usualy a bad approach. Every time the component is created, a redirect will occur. This includes refresh events and possibly other types outside of normal navigation.

    I would consider creating a guard that checks when is it required to redirect or not. However, this depends on the logic of your application since it this case so I can't help much more.