Angular 18: How to redirect on result of resolve

Discussão em 'Angular' iniciado por user2977624, Novembro 12, 2024.

  1. user2977624

    user2977624 Guest

    In Angular 18, I am trying to resolve a value before navigation, but redirect to another page based on that value.

    Please don't link to a page titled "Redirecting Guards and Resolvers in Angular v18" by Davide Passafaro. It doesn't answer my question.

    Here is the scenario:

    1. A path parameter is passed in the URL named key.
    2. I am using that key to obtain a value (that describes a piece of artwork) from the backend referenced by that key.
    3. If a valid value is returned I want that value bound to the component.
    4. If I receive a null value instead, I want to redirect to another page that displays a 404 - not found message.

    Here is what I have so far:

    const routes: Route = [
    path: ":key",
    component: ArtComponent,
    resolve: {
    art: () => inject(ArtService).get(key) // This automatically binds to a corresponding @Input() property on the component
    },
    canActivate: [
    () => {
    const router = inject(Router);
    *** somehow redirect to 404 page if art is null ***
    return true;
    }
    ]
    ];


    I'm obviously missing something. The alternative is to perform a redirect within the ngOnInit() function on the ArtComponent, but that sounds icky.

    Continue reading...

Compartilhe esta Página