How can I return true/false based on api response message in my angular authguard method?

tyro

I've put an angular routing authguard to put my page. I've an api that checks if the token is valid and based on that I want to return true or false for further navigation.

But seems that in 'subscribe' I assign my 'result' flag true not persisting outside of the subscribe. Is 'result' variable in wrong scope here? How can I correct that? Please help me understand my mistake in below code.

canActivate( next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
  const jwt = localStorage.getItem('jwt');
  let result = false;

  this.signinService.isSignedin(jwt).subscribe((res) => { // <---
    console.log(res.json().message);
    if (res.json().message === 'Token Valid') {
      result = true;
      console.log(result);
      return true;
    } else {
      result = false;
      return false;
    }
  }, (err) => { // <---
    console.log(err);
    result = false;
    return false;
  });
  console.log('END' + result);
  return result;}

The above code prints out on console in below order, which seems to be weird to me. Anyone can explain please?

ENDfalse

Token Valid

true

Jim

But seems that in 'subscribe' I assign my 'result' flag true not persisting outside of the subscribe.

I think you are not fully understanding how the interpreter will read and evaluate this code. Because the JavaScript event loop is never blocking, the interpreter will get to the subscribe block, make the request, and then continue along executing the code outside of the subscribe block without waiting for the response to come back. This is why "ENDfalse" is printed first. Then the response comes in and the callback function is executed with the line console.log(res.json().message); printing "Token Valid" and console.log(result); returning true.

One way you could fix this might be to return the whole observable and then subscribe to in the place where you actually want to use the value of "result" (and in fact your function signature of canActivate shows that you should be returning an observable, not the data).

canActivate( next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
  const jwt = localStorage.getItem('jwt');
  return this.signinService.isSignedin(jwt);
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How can I display my API response message on my frontend UI with React?

How can I return post API message?

i can't return a response value on my cypress api call

How can i create a retrofit api method call that doesnt return a response

How can I return all the response from API to my Swift app

How can I change a part of my html page based on the response of an api

How can I print the message in my method in my class?

How can I return regular response in override get method, Django

Scala slick how can I return my own Error message

How can I catch web api return message on Devextreme datagrid?

How can i return warning message from .NET CORE API

How i can return to my template a value based in a typescript decision?

How can I display my api response when user Login?

How can i make my method return a callback?

How can i set login Response detail in Angular API Request?

How can I return a common JSON object in my flask API?

How can I return the location of http created resource along with a response status message in JAX-RS?

How can I implement actions based on my rest API

Why i can't return my method?

How can I return custom hibernate validation message in my controller with i18n?

How can I return the Http response?

How can i send response message to SOAP Outbound Message in Salesforce

How can I read headers sent from my API with angular?

How can I see the full server response for this API error message in Google Scripts?

How can I make my code return a "Invalid number" message to a player if they type /launch <notaninteger> or /launch String

How do I return a JSON response message and an HTTP error code from javax.servlet.filter doFilter method?

How I can display dropdown menu list based on my code and JSON response object?

How do I return a valid ETag in a message's response?

How I can return Affected rows data from post API in response oracle DB and Node JS

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  3. 3

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  4. 4

    pump.io port in URL

  5. 5

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    Do Idle Snowflake Connections Use Cloud Services Credits?

  9. 9

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

  10. 10

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  11. 11

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  12. 12

    Generate random UUIDv4 with Elm

  13. 13

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  14. 14

    Is it possible to Redo commits removed by GitHub Desktop's Undo on a Mac?

  15. 15

    flutter: dropdown item programmatically unselect problem

  16. 16

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  17. 17

    EXCEL: Find sum of values in one column with criteria from other column

  18. 18

    Pandas - check if dataframe has negative value in any column

  19. 19

    How to use merge windows unallocated space into Ubuntu using GParted?

  20. 20

    Make a B+ Tree concurrent thread safe

  21. 21

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

HotTag

Archive