0

Hello guys here is my http post code

createPost(input:HTMLInputElement){
    // input.value='';
    let post={content:input.value};
    let head = new Headers({ 'Content-Type': 'application/json' });
    let requestOptions = new RequestOptions({headers: head});
    let body = JSON.stringify(post);

    this.http.post(this.url,body,requestOptions)
      .subscribe(response => {
        post['id']=response.json().id;
        this.posts.splice(0,0,post);
      });

after a successfull http post request my server responds with a token for authentication to make that request, the token would be in JSON format. Now is there any way where I can get that token in real time and store it in local storage directly after a http post call

I can understand the concept of localStorage.getItem() and all but don't know where to implement them exactly to the context of my code this question might be so dumb to you but I'm just beginner in Angular

1
  • 1
    Don't really understand the question? Simply do a localStorage.setItem('myToken', theToken), right after the response Commented Aug 2, 2018 at 6:21

1 Answer 1

1

You can have an LoginService which gets your token and saves it in the localStorage. It also can have another method with name isAuthenticated which verifies client is authenticated or not. When you have done the request

this.http.post(this.url,body,requestOptions)
         .subscribe(response => {
            post['id']=response.json().id;
            this.posts.splice(0,0,post);
            // Here you need to store the token in the localStorage
            // localStorage.setItem('access_token', yourToken)
         });

you need to store the token in the localStorage and then use this service to do next operations related to the token.

Another methods can look like

getToken() : string {
   return localStorage.getItem('access_tojen');
}

isAuthenticated() : boolean {
   const token = getToken();
   return /* your logic here */.
}

You can also look at a post about Authentication.

Sign up to request clarification or add additional context in comments.

9 Comments

directly how can i get the token like grabbing the token using after a http post request how the code would look like
Mounikesh: lets take an example http.post(example.com/token) and now user is logged in and token is visible for him in the token of my site now angular should should get that token and save it to localstorage in real time
There are libraries which decode your token and get the payload from it. For first you need to get the token.
no need to decode or anything just the token is enough to authenticate users
But maybe you also need for example name of the user, or role - I mean that
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.