Aurelia 2 - How do I redirect to a route in canLoad Lifecycle hook

How do I redirect to a specific route in canLoad Lifecycle hook?

I am checking if a certain condition is true in the canLoad lifcycle hook of one of my route. If it is false I would like to redirect to another view?

async canLoad(params) {
    let respose = await someAPIcall()
    
    if(response.something === true) {
        return this.router.load('newRoute')
    }
  
  return true
}

This just makes the page go blank with no error messages

Another way to go is this:

import Component1 from './c1'
import Component2 from './c2'

async canLoad(params) {
    let respose = await someAPIcall()
    
    if(response.something === true) {
        return Component1
    }

    if(response.somethingElse === true) {
        return Component2
    }
  
  return true
}

This works! However, how do you pass parameter like this? Say component2 is defined like this:

{ id: 'c2', path: 'c2/:id', component: import('./resources/routes/Component2'), title: 'C2' }

How do I pass the id paramerter?

2 Likes

Some progress:

Instead of

return Component2

used

return this.router.createViewportInstructions({ component: Component2, params: { id: params.id } })

This works in a way, however, the url is incorrect:

http://localhost:9000/component2(id=d178d5f4)

Should be

http://localhost:9000/component2/d178d5f4
2 Likes

Never mind folks, turns out I was overthinking it. You can just return the name of the route e.g.

if(response.something === true) {
   return 'component1'
 }

  if(response.somethingElse === true) {
        return 'component2/123abc'
 }
3 Likes