[Resolved] Routes: checking for a condition before redirecting

Hello,

Let’s say I have this in my routes:
{
path: ‘/post/:userid/:postid,
template:’

{{$route.params.userid}} - {{$route.params.postid}}
’,
}

Before this page loads, I want to check if the record exists so I would use an AJAX call for that. If the response is true, then the page should continue loading. If it’s false, I want to redirect it to the 404 page.

I tried redirect:
redirect: function (route, resolve, reject) {
app.request.post(‘checkifpostexists.php’,{ postid:route.params.postid}, function (data) {
if(data==“true”){
resolve(’/post/’+route.params.userid+’/’+route.params.postid);
}else{
reject();
}
});
}

But I only get an endless loop. Probably because it’s already in /post/, and I still try to redirect it to /post/.

beforeEnter and beforeLeave do not work for me either. Should I use async? If so, how?

Thanks in advance!

You get an endless loop because this is what your code actually does. Use route’s async or beforeEnter to achieve this. Check also this blog post https://blog.framework7.io/mastering-v2-router-958ea2dbd24f

Hello,

Thanks for your response. Yeah I figured that must be why it’s in an endless loop. Haha! I got something working by using redirect: and setting a different page so it won’t get stuck in an endless loop. But I want to do it correctly so I gave async another try. Here’s the code:

{
    path: '/post/:userid/:postid',
    async: function(routeTo, routeFrom, resolve, reject) {
      app.request.post('checkifpostexists.php',{postid:route.params.postid}, function (data) {
      if(data=="true"){
        resolve({
          template: '<div class="page">Post exists.</div>'
        });
      } else {
        resolve({
          template: '<div class="page">Post doesn't exist.</div>'
        });
      }
    });
} 

The code checks if the post exists before displaying the appropriate content. If the request returns true, it will say “Post exists”, and if not, “Post doesn’t exist”. It works great if I give the app.request.post’s postid parameter a constant value, like 66, or 70. However, it gives me a “route is not defined” error if I try to use the value of :postid as route.params.postid. Why is that? I will add that it worked when I used redirect:.

What should I use instead of route.params.postid so the request will use whatever the value :postid has?

Thanks!

Didn’t get what is the issue. Give more details what is there when it does not work?

Hi Vladimir,

I was actually about to give an update to this post because I was able to figure it out. I wanted to use userid as a parameter for app.request.post parameter. I initially used {postid:route.params.postid} but it says “route is not defined” on the console. I checked out the content of routeTo and it turns out I just need to use { postid:routeTo.params.postid} instead.

Thanks! :slight_smile:

1 Like