Angular HttpClient & Observables

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Angular HttpClient & Observables



I'm trying to write a TypeScript method for my Angular web app that simply checks the validity of a JWT token on the server with an Http call.



I want this method to return a boolean value, telling my caller if the token is valid or not. I come from C# so i would expect I can do something like this and I haven't got a clear idea of how function returns are managed in JS/TS:


verifyCanActivate(): boolean

const actionUrl = this.apiBaseUrl + 'ValidateToken';

this.http.get(actionUrl)
.map((data: HttpResponse<any>) => data.status === 200);



An Http interceptor has already been set up, so every request I make is automatically decorated with header authentication info.



My server-side action for this controller is an empty ASP.NET Core WebAPI method, flagged with the [Authorize] attribute so I can easily check the validity of client tokens every time a call is made.



How do I have to write my TS method so it can return a boolean value based on the HttpResponse Status? I would also appreciate if you can provide a useful and up-to-date documentation about this topic in general.


boolean


HttpResponse



Thank you in advance.





Do you want to call the method synchronously? Or is it acceptable to you to change the way the method is used, i.e., calling it asynchronously? I ask because you will probably be told to return an observable from this method.
– DrSatan1
Aug 10 at 9:02






btw, just out of curiosity > why would you want explicit JWT validation check endpoint since you already have interceptor which makes your jwt checked on each and every call to endpoints decorated with [Authorize]?
– dee zg
Aug 10 at 9:13



[Authorize]





@deezg Is there a way to integrate the interceptor validation with the angular routing guard system?
– moro91
Aug 10 at 9:32





why would you integrate it with angular routing? its 2 separate things. you should have some state (jwt token) in your application (don't know if you use ngrx or some state management) that indicates if user did login successfuly or not. that state check goes into guard. then, completely separated, all your api calls will be added aurhotization header & jwt (that happens in interceptor). now, when your [Authorize] decorated endpoint gets hit by unauthorized user (or expired jwt) it should return 401. That's what you handle in interceptor and redirect to login page.
– dee zg
Aug 10 at 9:42



[Authorize]


401




3 Answers
3



Your verifyCanActivate method should return Observable<boolean> and then when you actually use it (read, subscribe to it) you'd get your boolean value.


verifyCanActivate


Observable<boolean>



So, something like this:


verifyCanActivate(): Observable<boolean>

const actionUrl = this.apiBaseUrl + 'ValidateToken';

return this.http.get(actionUrl)
.map((data: HttpResponse<any>) => data.status === 200);



(notice return > you're returning this.http.get observable)


this.http.get



and then you use it like:


verifyCanActivate().subscribe(responseValue => console.log(returnValue));





This worked perfectly! Thank you!
– moro91
Aug 10 at 9:34



In angular HttpClient return the response as an observable. You can define the data type of the observable but anyway it returns an observable. so you have to modify the return type of your method like this.


verifyCanActivate(): Observable<boolean> {



Since the Observables are asynchronous you can't directly access the values returned from the server. you need to subscribe to observable and then only we can access the data.


verifyCanActivate().subscribe( (result: boolean) =>
console.log(result) // the boolean value
)



Like the other answers already said, your method returns an Observable<boolean> which you can subscribe to. But to get the status of the HttpResponse, you need to add the observe: 'response' HttpOption. Otherwise you can only view the Response - Body.


Observable<boolean>


HttpResponse


observe: 'response' HttpOption


verifyCanActivate(): Observable<HttpResponse<any>>

const actionUrl = this.apiBaseUrl + 'ValidateToken';

return this.http.get(actionUrl, observe: 'response' );



And your Subscription should be like this:


verifyCanActivate().subscribe((response: HttpResponse<any>) =>
response.status === 200
);






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

Creating a leaderboard in HTML/JS