0

I currently have the following service:

@Injectable()
export class UserServiceService {
  userEmail: string;
  userPassword: string;

  constructor( private http: HttpClient ) { }

  login( userEmail, userPassword ){
    let body = { "email": userEmail, "password": userPassword};

    this.http.post('/customer/service/logging', body, httpOptions).subscribe(
      data => {
        console.log( data );
      },
      error => {
        console.error("There Is Something Wrong\nPlease Try Again Later...");
      }
    );

  }
}

At run-time the post, if successful, returns the following object:

{message: "Login Successful", status: "success"}

What I want to do is to take the key status and use it for routing (if successful), then the key message to alert the user that his/her login went successfully / not.

How can I take this keys and values and use them, as mentioned above?

2
  • you can use "canActivate" route guards for that. Commented Jan 22, 2018 at 9:11
  • Please provide me with example on regards to the solution Commented Jan 22, 2018 at 9:30

2 Answers 2

1
this.http.post('/customer/service/logging', body, httpOptions).subscribe(
  data => {
    if(data.status === 'success'){
        alert(data.message); //or do whatever you want 
     }else {
     alert('login fails'); // or alert(data.message) with the error message from the server
    }
  },
  error => {
    console.error("There Is Something Wrong\nPlease Try Again Later...");
  }
);
Sign up to request clarification or add additional context in comments.

4 Comments

data.status gives me an error, is there any imports I have to make?
use console.log(data) to check the object you're returning from the server...if it is indeed what you mentioned, data.status wouldn't give an error
I know why it was screaming; it wanted the http to have a return, for e.g. this.http.post<any>('/customer/se...
but typing the method is not mandatory, why is asking you to type it? in any case...did you manage to access data.status?
0

you should convert it to json at first

this.http.post('/customer/service/logging', body, httpOptions)
.subscribe(
  data => {
    let res = data.json();
    console.log( res.status);

  },
  error => {
    console.error("There Is Something Wrong\nPlease Try Again Later...");
  }
);

2 Comments

if I'm not mistaken, HttpClient does not need the map function anymore.
Yep, that's what the doc says

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.