Search code examples
angularangular-routing

Button does different things depending on where i've placed the logic


can anyone explain to me why the 'all-movies' route does a GET request to my API when i place it where it is right now, but when i place it on top of 'create' it does the redirect, as it is supposed to. Here is the code :

const routes: Routes = [
 
  {
    path: 'create',
    component: CreateComponent,
    canActivate: [MovieGuardService]
  },
  {
    path: ':id',
    resolve: {
      cres: MovieResolver,
    },
    component: MovieComponent,
  },
  {
    path: ':id/edit',
    resolve: {
      cres: MovieResolver,
    },
    component: EditComponent,
    canActivate: [MovieGuardService]
  },
  {
    path: 'all-movies',
    component: AllMoviesComponent
   },

];

Solution

  • The order of routes in Angular's Routes array is important because the router matches the URL against the defined routes in a sequential manner. When a URL is entered, the router tries to find a match starting from the top of the array and continues until it finds a match or reaches the end of the array.

    In your code, the all-movies route is placed at the bottom of the routes array. When you navigate to the /all-movies URL, the router matches the URL against the routes sequentially. Since the :id parameter in the route /:id is a generic parameter that can match any value, the router considers /all-movies as a valid :id parameter and directs the request to the MovieComponent instead of the AllMoviesComponent.