2
votes

I am desperately to implement a navigation guard that will prevent users to access an item page if the item doesn't exist, based on the ID provided in route params.

It says in the Vue-Router guide that:

next(false): abort the current navigation. If the browser URL was changed(either manually by the user or via back button), it will be reset to that of the from route.

Yet in my component, using next(false) won't prevent the route change, or component rendering. It won't even navigate back as promised in the doc.

beforeRouteEnter(to, from, next) {
    next(false)
    ajaxcall$.subscribe(data => next(vm => vm.setData(data)))

I would have expected that obvious next(false) to work and prevent the component and route from rendering but nope. The ajax call is made and the data is set.

1
you should add a return statement to avoid executing the following expressions (i.e. return next(false)).Eliran Malka
I think next is a callback. I don't think callbacks should be return values. It would break things.igreka
it does not matter which value is returned (or if a value is returned). the point is you should return immediately after the callback invocation.Eliran Malka

1 Answers

1
votes

"Make sure that the next function is called exactly once in any given pass through the navigation guard." Vue Router - Global Before Guards

You have multiple next() calls.

Also, your ajaxcall$.subscribe() is most likely an async method, so by the time it calls next(vm => vm.setData(data)) the navigation has happened most probably.

You should use await to make sure the information from ajax is available before calling next().

It might not really be a good idea to slow down each page transition with an API call, but that's a different issue...