Lahiru idangoda
Lahiru idangoda

Reputation: 45

Separating data from a httpResponse body in Angular

I am very new to Angular. I am required to separate out the 'jwt' token from the response in the component to store it in the localstorage. Can't get the response as a text since I require the response.status as well. Can someone show me how to separate it out? I tried many explanations here, but nothing seems to work out for me.

My login method;

checkLogin(){
this.service.generateToken(this.credentials).subscribe(
  (response) => {
    if(response.status == 200){
      this.message = "Login Successfull"
      localStorage.setItem("token",//save the token);
      this.router.navigate(['']);
    }
},
(error) => {
    this.message = "Invalid Username or Password";
});
}

The http service

public generateToken(request):Observable<any>{
return this.http.post<any>("http://localhost:8080/authenticate", request,{observe:'response'});
}

My Response format:

Response Format

Upvotes: 1

Views: 87

Answers (1)

ravi
ravi

Reputation: 1145

if you are able to get response.status value then response.body.jwt would also be accessible, can you try this way

(response) => {
    if(response.status == 200){
      this.message = "Login Successfull"
      localStorage.setItem("token",response.body.jwt);
      this.router.navigate(['']);
    }

Upvotes: 1

Related Questions