API call in canactivate method in Angular











up vote
2
down vote

favorite
1












I am using canActivate using guards in Angular. I want to check if the user is authenticated and based on the result protect the route.
There are two types of users: Type1 and Type2, so user can be either authenticated with Type1, Type2 or unauthenticated.
The following guard is for Type1 user.



Here is my code:



constructor(private authservice: AuthService, private router: Router, private route: ActivatedRoute){}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean{

const self = this;
const expectedType = "type1";

this.authservice.isUserAuthenticatedbyType(expectedType).then(
function(data){
if(data === false){
console.log(data);
self.router.navigate(['/'], {relativeTo: self.route});
}
return data;
},
function(error){
self.router.navigate(['/']);
return false;
}
);
return false;
}


The problem is I make an API call to validate if the user is authenticated and return false; is executed before the result from the API. So, momentarily I see a different page and then it is routed to the correct page. How can I fix this, I do not want to return false or true before the API call, but not doing that gives an error.



I also tried the following:



return this.authservice.isUserAuthenticatedbyType(expectedType)


But this simply navigates me to the http://localhost:4200 url in case of unauthenticated user.



I have the following route:



{ path: "", component: HomeComponent },


So, in the above scenario, HomeComponent should have been called, but ngOnInit of HomeComponent is not getting called.










share|improve this question
























  • Return an Observable<boolean>, not a boolean.
    – JB Nizet
    Nov 17 at 15:13










  • Doing return this.authservice.isUserAuthenticatedbyType(expectedType) should work from the look of it
    – user184994
    Nov 17 at 15:14










  • @user184994 Yes but it is navigating to http://localhost:4200 but HomeComponent ngOnInit is not called where I have some logic to execute.
    – helloworld
    Nov 17 at 15:15















up vote
2
down vote

favorite
1












I am using canActivate using guards in Angular. I want to check if the user is authenticated and based on the result protect the route.
There are two types of users: Type1 and Type2, so user can be either authenticated with Type1, Type2 or unauthenticated.
The following guard is for Type1 user.



Here is my code:



constructor(private authservice: AuthService, private router: Router, private route: ActivatedRoute){}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean{

const self = this;
const expectedType = "type1";

this.authservice.isUserAuthenticatedbyType(expectedType).then(
function(data){
if(data === false){
console.log(data);
self.router.navigate(['/'], {relativeTo: self.route});
}
return data;
},
function(error){
self.router.navigate(['/']);
return false;
}
);
return false;
}


The problem is I make an API call to validate if the user is authenticated and return false; is executed before the result from the API. So, momentarily I see a different page and then it is routed to the correct page. How can I fix this, I do not want to return false or true before the API call, but not doing that gives an error.



I also tried the following:



return this.authservice.isUserAuthenticatedbyType(expectedType)


But this simply navigates me to the http://localhost:4200 url in case of unauthenticated user.



I have the following route:



{ path: "", component: HomeComponent },


So, in the above scenario, HomeComponent should have been called, but ngOnInit of HomeComponent is not getting called.










share|improve this question
























  • Return an Observable<boolean>, not a boolean.
    – JB Nizet
    Nov 17 at 15:13










  • Doing return this.authservice.isUserAuthenticatedbyType(expectedType) should work from the look of it
    – user184994
    Nov 17 at 15:14










  • @user184994 Yes but it is navigating to http://localhost:4200 but HomeComponent ngOnInit is not called where I have some logic to execute.
    – helloworld
    Nov 17 at 15:15













up vote
2
down vote

favorite
1









up vote
2
down vote

favorite
1






1





I am using canActivate using guards in Angular. I want to check if the user is authenticated and based on the result protect the route.
There are two types of users: Type1 and Type2, so user can be either authenticated with Type1, Type2 or unauthenticated.
The following guard is for Type1 user.



Here is my code:



constructor(private authservice: AuthService, private router: Router, private route: ActivatedRoute){}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean{

const self = this;
const expectedType = "type1";

this.authservice.isUserAuthenticatedbyType(expectedType).then(
function(data){
if(data === false){
console.log(data);
self.router.navigate(['/'], {relativeTo: self.route});
}
return data;
},
function(error){
self.router.navigate(['/']);
return false;
}
);
return false;
}


The problem is I make an API call to validate if the user is authenticated and return false; is executed before the result from the API. So, momentarily I see a different page and then it is routed to the correct page. How can I fix this, I do not want to return false or true before the API call, but not doing that gives an error.



I also tried the following:



return this.authservice.isUserAuthenticatedbyType(expectedType)


But this simply navigates me to the http://localhost:4200 url in case of unauthenticated user.



I have the following route:



{ path: "", component: HomeComponent },


So, in the above scenario, HomeComponent should have been called, but ngOnInit of HomeComponent is not getting called.










share|improve this question















I am using canActivate using guards in Angular. I want to check if the user is authenticated and based on the result protect the route.
There are two types of users: Type1 and Type2, so user can be either authenticated with Type1, Type2 or unauthenticated.
The following guard is for Type1 user.



Here is my code:



constructor(private authservice: AuthService, private router: Router, private route: ActivatedRoute){}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean{

const self = this;
const expectedType = "type1";

this.authservice.isUserAuthenticatedbyType(expectedType).then(
function(data){
if(data === false){
console.log(data);
self.router.navigate(['/'], {relativeTo: self.route});
}
return data;
},
function(error){
self.router.navigate(['/']);
return false;
}
);
return false;
}


The problem is I make an API call to validate if the user is authenticated and return false; is executed before the result from the API. So, momentarily I see a different page and then it is routed to the correct page. How can I fix this, I do not want to return false or true before the API call, but not doing that gives an error.



I also tried the following:



return this.authservice.isUserAuthenticatedbyType(expectedType)


But this simply navigates me to the http://localhost:4200 url in case of unauthenticated user.



I have the following route:



{ path: "", component: HomeComponent },


So, in the above scenario, HomeComponent should have been called, but ngOnInit of HomeComponent is not getting called.







angular






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 17 at 15:16

























asked Nov 17 at 15:11









helloworld

748




748












  • Return an Observable<boolean>, not a boolean.
    – JB Nizet
    Nov 17 at 15:13










  • Doing return this.authservice.isUserAuthenticatedbyType(expectedType) should work from the look of it
    – user184994
    Nov 17 at 15:14










  • @user184994 Yes but it is navigating to http://localhost:4200 but HomeComponent ngOnInit is not called where I have some logic to execute.
    – helloworld
    Nov 17 at 15:15


















  • Return an Observable<boolean>, not a boolean.
    – JB Nizet
    Nov 17 at 15:13










  • Doing return this.authservice.isUserAuthenticatedbyType(expectedType) should work from the look of it
    – user184994
    Nov 17 at 15:14










  • @user184994 Yes but it is navigating to http://localhost:4200 but HomeComponent ngOnInit is not called where I have some logic to execute.
    – helloworld
    Nov 17 at 15:15
















Return an Observable<boolean>, not a boolean.
– JB Nizet
Nov 17 at 15:13




Return an Observable<boolean>, not a boolean.
– JB Nizet
Nov 17 at 15:13












Doing return this.authservice.isUserAuthenticatedbyType(expectedType) should work from the look of it
– user184994
Nov 17 at 15:14




Doing return this.authservice.isUserAuthenticatedbyType(expectedType) should work from the look of it
– user184994
Nov 17 at 15:14












@user184994 Yes but it is navigating to http://localhost:4200 but HomeComponent ngOnInit is not called where I have some logic to execute.
– helloworld
Nov 17 at 15:15




@user184994 Yes but it is navigating to http://localhost:4200 but HomeComponent ngOnInit is not called where I have some logic to execute.
– helloworld
Nov 17 at 15:15












2 Answers
2






active

oldest

votes

















up vote
1
down vote



accepted










You can achieve it like this:



Angular <= 7.0.0



public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
return this.authservice.isUserAuthenticatedbyType("type1").pipe(
map(data => {
if (data === false) {
this.router.navigate(['/']);
return false;
}

return !!data;
}),
catchError(() => {
this.router.navigate(['/']);
return of(false);
}),
);
}


Angular >= 7.1.0



Starting with Angular 7.1.0 (note that it's not in 7.0.x), you can also do this instead, which is shorter and more predictable if you have multiple guards:



public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
return this.authservice.isUserAuthenticatedbyType("type1").pipe(
map(data => data === false ? this.router.parseUrl("/") : !!data)
catchError(() => this.router.parseUrl("/")),
);
}





share|improve this answer





















  • Thanks. I am using Angular 6 and rxjx version 6.2.1 but I get the following error: Property 'pipe' does not exist on type 'Promise<boolean>. Also, can you please explain what I was doing wrong, if possible.
    – helloworld
    Nov 17 at 18:22






  • 1




    It sounds like your service method is returning a Promise, not an observable. You can use fromPromise(this.authservice.isUserAuthenticatedbyType("type1")) to convert it into an observable on which you can then use pipe. What you were doing wrong was that you synchronously returned an answer from the guard but only asynchronously were able to redirect. My solution defers the answer from the guard until the redirect actually happens.
    – Ingo Bürk
    Nov 17 at 19:29










  • Thanks, but I am still not able to understand when I was simply returning the following: return this.authservice.isUserAuthenticatedbyType(expectedType), why was I getting redirected to localhost:4200 and still HomeComponent was not getting called?
    – helloworld
    Nov 17 at 21:04






  • 1




    Without any redirect, if the guard rejects the navigation, the navigation just fails. There's no automatic redirect to the root route or anything like that. It just rejects the navigation attempt.
    – Ingo Bürk
    Nov 17 at 22:08


















up vote
1
down vote













If you are using promise try something like this - main idea is to hold your routing until your Api call is done - I had the same issue, I have achieved it by returning Promise<boolean> on my route gaurds



    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean{
const self = this;
const expectedType = "type1";
retrun new Promise(res => {
this.authservice.isUserAuthenticatedbyType(expectedType).then(
function (data) {
if (data === false) {
console.log(data);
self.router.navigate(['/'], { relativeTo: self.route });
}
res(data);
},
function (error) {
self.router.navigate(['/']);
res(false);
}
);
});
}


This method solved my issue - it waits until the API returns data and gives direction to the route



Hope it will work - Happy coding !!






share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














     

    draft saved


    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53352510%2fapi-call-in-canactivate-method-in-angular%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    1
    down vote



    accepted










    You can achieve it like this:



    Angular <= 7.0.0



    public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    return this.authservice.isUserAuthenticatedbyType("type1").pipe(
    map(data => {
    if (data === false) {
    this.router.navigate(['/']);
    return false;
    }

    return !!data;
    }),
    catchError(() => {
    this.router.navigate(['/']);
    return of(false);
    }),
    );
    }


    Angular >= 7.1.0



    Starting with Angular 7.1.0 (note that it's not in 7.0.x), you can also do this instead, which is shorter and more predictable if you have multiple guards:



    public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    return this.authservice.isUserAuthenticatedbyType("type1").pipe(
    map(data => data === false ? this.router.parseUrl("/") : !!data)
    catchError(() => this.router.parseUrl("/")),
    );
    }





    share|improve this answer





















    • Thanks. I am using Angular 6 and rxjx version 6.2.1 but I get the following error: Property 'pipe' does not exist on type 'Promise<boolean>. Also, can you please explain what I was doing wrong, if possible.
      – helloworld
      Nov 17 at 18:22






    • 1




      It sounds like your service method is returning a Promise, not an observable. You can use fromPromise(this.authservice.isUserAuthenticatedbyType("type1")) to convert it into an observable on which you can then use pipe. What you were doing wrong was that you synchronously returned an answer from the guard but only asynchronously were able to redirect. My solution defers the answer from the guard until the redirect actually happens.
      – Ingo Bürk
      Nov 17 at 19:29










    • Thanks, but I am still not able to understand when I was simply returning the following: return this.authservice.isUserAuthenticatedbyType(expectedType), why was I getting redirected to localhost:4200 and still HomeComponent was not getting called?
      – helloworld
      Nov 17 at 21:04






    • 1




      Without any redirect, if the guard rejects the navigation, the navigation just fails. There's no automatic redirect to the root route or anything like that. It just rejects the navigation attempt.
      – Ingo Bürk
      Nov 17 at 22:08















    up vote
    1
    down vote



    accepted










    You can achieve it like this:



    Angular <= 7.0.0



    public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    return this.authservice.isUserAuthenticatedbyType("type1").pipe(
    map(data => {
    if (data === false) {
    this.router.navigate(['/']);
    return false;
    }

    return !!data;
    }),
    catchError(() => {
    this.router.navigate(['/']);
    return of(false);
    }),
    );
    }


    Angular >= 7.1.0



    Starting with Angular 7.1.0 (note that it's not in 7.0.x), you can also do this instead, which is shorter and more predictable if you have multiple guards:



    public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    return this.authservice.isUserAuthenticatedbyType("type1").pipe(
    map(data => data === false ? this.router.parseUrl("/") : !!data)
    catchError(() => this.router.parseUrl("/")),
    );
    }





    share|improve this answer





















    • Thanks. I am using Angular 6 and rxjx version 6.2.1 but I get the following error: Property 'pipe' does not exist on type 'Promise<boolean>. Also, can you please explain what I was doing wrong, if possible.
      – helloworld
      Nov 17 at 18:22






    • 1




      It sounds like your service method is returning a Promise, not an observable. You can use fromPromise(this.authservice.isUserAuthenticatedbyType("type1")) to convert it into an observable on which you can then use pipe. What you were doing wrong was that you synchronously returned an answer from the guard but only asynchronously were able to redirect. My solution defers the answer from the guard until the redirect actually happens.
      – Ingo Bürk
      Nov 17 at 19:29










    • Thanks, but I am still not able to understand when I was simply returning the following: return this.authservice.isUserAuthenticatedbyType(expectedType), why was I getting redirected to localhost:4200 and still HomeComponent was not getting called?
      – helloworld
      Nov 17 at 21:04






    • 1




      Without any redirect, if the guard rejects the navigation, the navigation just fails. There's no automatic redirect to the root route or anything like that. It just rejects the navigation attempt.
      – Ingo Bürk
      Nov 17 at 22:08













    up vote
    1
    down vote



    accepted







    up vote
    1
    down vote



    accepted






    You can achieve it like this:



    Angular <= 7.0.0



    public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    return this.authservice.isUserAuthenticatedbyType("type1").pipe(
    map(data => {
    if (data === false) {
    this.router.navigate(['/']);
    return false;
    }

    return !!data;
    }),
    catchError(() => {
    this.router.navigate(['/']);
    return of(false);
    }),
    );
    }


    Angular >= 7.1.0



    Starting with Angular 7.1.0 (note that it's not in 7.0.x), you can also do this instead, which is shorter and more predictable if you have multiple guards:



    public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    return this.authservice.isUserAuthenticatedbyType("type1").pipe(
    map(data => data === false ? this.router.parseUrl("/") : !!data)
    catchError(() => this.router.parseUrl("/")),
    );
    }





    share|improve this answer












    You can achieve it like this:



    Angular <= 7.0.0



    public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    return this.authservice.isUserAuthenticatedbyType("type1").pipe(
    map(data => {
    if (data === false) {
    this.router.navigate(['/']);
    return false;
    }

    return !!data;
    }),
    catchError(() => {
    this.router.navigate(['/']);
    return of(false);
    }),
    );
    }


    Angular >= 7.1.0



    Starting with Angular 7.1.0 (note that it's not in 7.0.x), you can also do this instead, which is shorter and more predictable if you have multiple guards:



    public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    return this.authservice.isUserAuthenticatedbyType("type1").pipe(
    map(data => data === false ? this.router.parseUrl("/") : !!data)
    catchError(() => this.router.parseUrl("/")),
    );
    }






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Nov 17 at 16:48









    Ingo Bürk

    10k43374




    10k43374












    • Thanks. I am using Angular 6 and rxjx version 6.2.1 but I get the following error: Property 'pipe' does not exist on type 'Promise<boolean>. Also, can you please explain what I was doing wrong, if possible.
      – helloworld
      Nov 17 at 18:22






    • 1




      It sounds like your service method is returning a Promise, not an observable. You can use fromPromise(this.authservice.isUserAuthenticatedbyType("type1")) to convert it into an observable on which you can then use pipe. What you were doing wrong was that you synchronously returned an answer from the guard but only asynchronously were able to redirect. My solution defers the answer from the guard until the redirect actually happens.
      – Ingo Bürk
      Nov 17 at 19:29










    • Thanks, but I am still not able to understand when I was simply returning the following: return this.authservice.isUserAuthenticatedbyType(expectedType), why was I getting redirected to localhost:4200 and still HomeComponent was not getting called?
      – helloworld
      Nov 17 at 21:04






    • 1




      Without any redirect, if the guard rejects the navigation, the navigation just fails. There's no automatic redirect to the root route or anything like that. It just rejects the navigation attempt.
      – Ingo Bürk
      Nov 17 at 22:08


















    • Thanks. I am using Angular 6 and rxjx version 6.2.1 but I get the following error: Property 'pipe' does not exist on type 'Promise<boolean>. Also, can you please explain what I was doing wrong, if possible.
      – helloworld
      Nov 17 at 18:22






    • 1




      It sounds like your service method is returning a Promise, not an observable. You can use fromPromise(this.authservice.isUserAuthenticatedbyType("type1")) to convert it into an observable on which you can then use pipe. What you were doing wrong was that you synchronously returned an answer from the guard but only asynchronously were able to redirect. My solution defers the answer from the guard until the redirect actually happens.
      – Ingo Bürk
      Nov 17 at 19:29










    • Thanks, but I am still not able to understand when I was simply returning the following: return this.authservice.isUserAuthenticatedbyType(expectedType), why was I getting redirected to localhost:4200 and still HomeComponent was not getting called?
      – helloworld
      Nov 17 at 21:04






    • 1




      Without any redirect, if the guard rejects the navigation, the navigation just fails. There's no automatic redirect to the root route or anything like that. It just rejects the navigation attempt.
      – Ingo Bürk
      Nov 17 at 22:08
















    Thanks. I am using Angular 6 and rxjx version 6.2.1 but I get the following error: Property 'pipe' does not exist on type 'Promise<boolean>. Also, can you please explain what I was doing wrong, if possible.
    – helloworld
    Nov 17 at 18:22




    Thanks. I am using Angular 6 and rxjx version 6.2.1 but I get the following error: Property 'pipe' does not exist on type 'Promise<boolean>. Also, can you please explain what I was doing wrong, if possible.
    – helloworld
    Nov 17 at 18:22




    1




    1




    It sounds like your service method is returning a Promise, not an observable. You can use fromPromise(this.authservice.isUserAuthenticatedbyType("type1")) to convert it into an observable on which you can then use pipe. What you were doing wrong was that you synchronously returned an answer from the guard but only asynchronously were able to redirect. My solution defers the answer from the guard until the redirect actually happens.
    – Ingo Bürk
    Nov 17 at 19:29




    It sounds like your service method is returning a Promise, not an observable. You can use fromPromise(this.authservice.isUserAuthenticatedbyType("type1")) to convert it into an observable on which you can then use pipe. What you were doing wrong was that you synchronously returned an answer from the guard but only asynchronously were able to redirect. My solution defers the answer from the guard until the redirect actually happens.
    – Ingo Bürk
    Nov 17 at 19:29












    Thanks, but I am still not able to understand when I was simply returning the following: return this.authservice.isUserAuthenticatedbyType(expectedType), why was I getting redirected to localhost:4200 and still HomeComponent was not getting called?
    – helloworld
    Nov 17 at 21:04




    Thanks, but I am still not able to understand when I was simply returning the following: return this.authservice.isUserAuthenticatedbyType(expectedType), why was I getting redirected to localhost:4200 and still HomeComponent was not getting called?
    – helloworld
    Nov 17 at 21:04




    1




    1




    Without any redirect, if the guard rejects the navigation, the navigation just fails. There's no automatic redirect to the root route or anything like that. It just rejects the navigation attempt.
    – Ingo Bürk
    Nov 17 at 22:08




    Without any redirect, if the guard rejects the navigation, the navigation just fails. There's no automatic redirect to the root route or anything like that. It just rejects the navigation attempt.
    – Ingo Bürk
    Nov 17 at 22:08












    up vote
    1
    down vote













    If you are using promise try something like this - main idea is to hold your routing until your Api call is done - I had the same issue, I have achieved it by returning Promise<boolean> on my route gaurds



        canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean{
    const self = this;
    const expectedType = "type1";
    retrun new Promise(res => {
    this.authservice.isUserAuthenticatedbyType(expectedType).then(
    function (data) {
    if (data === false) {
    console.log(data);
    self.router.navigate(['/'], { relativeTo: self.route });
    }
    res(data);
    },
    function (error) {
    self.router.navigate(['/']);
    res(false);
    }
    );
    });
    }


    This method solved my issue - it waits until the API returns data and gives direction to the route



    Hope it will work - Happy coding !!






    share|improve this answer

























      up vote
      1
      down vote













      If you are using promise try something like this - main idea is to hold your routing until your Api call is done - I had the same issue, I have achieved it by returning Promise<boolean> on my route gaurds



          canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean{
      const self = this;
      const expectedType = "type1";
      retrun new Promise(res => {
      this.authservice.isUserAuthenticatedbyType(expectedType).then(
      function (data) {
      if (data === false) {
      console.log(data);
      self.router.navigate(['/'], { relativeTo: self.route });
      }
      res(data);
      },
      function (error) {
      self.router.navigate(['/']);
      res(false);
      }
      );
      });
      }


      This method solved my issue - it waits until the API returns data and gives direction to the route



      Hope it will work - Happy coding !!






      share|improve this answer























        up vote
        1
        down vote










        up vote
        1
        down vote









        If you are using promise try something like this - main idea is to hold your routing until your Api call is done - I had the same issue, I have achieved it by returning Promise<boolean> on my route gaurds



            canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean{
        const self = this;
        const expectedType = "type1";
        retrun new Promise(res => {
        this.authservice.isUserAuthenticatedbyType(expectedType).then(
        function (data) {
        if (data === false) {
        console.log(data);
        self.router.navigate(['/'], { relativeTo: self.route });
        }
        res(data);
        },
        function (error) {
        self.router.navigate(['/']);
        res(false);
        }
        );
        });
        }


        This method solved my issue - it waits until the API returns data and gives direction to the route



        Hope it will work - Happy coding !!






        share|improve this answer












        If you are using promise try something like this - main idea is to hold your routing until your Api call is done - I had the same issue, I have achieved it by returning Promise<boolean> on my route gaurds



            canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean{
        const self = this;
        const expectedType = "type1";
        retrun new Promise(res => {
        this.authservice.isUserAuthenticatedbyType(expectedType).then(
        function (data) {
        if (data === false) {
        console.log(data);
        self.router.navigate(['/'], { relativeTo: self.route });
        }
        res(data);
        },
        function (error) {
        self.router.navigate(['/']);
        res(false);
        }
        );
        });
        }


        This method solved my issue - it waits until the API returns data and gives direction to the route



        Hope it will work - Happy coding !!







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 17 at 18:50









        Rahul Swamynathan

        796212




        796212






























             

            draft saved


            draft discarded



















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53352510%2fapi-call-in-canactivate-method-in-angular%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Paul Cézanne

            UIScrollView CustomStickyHeader Resize height generates problems when scroll is too fast

            Angular material date-picker (MatDatepicker) auto completes the date on focus out