Search code examples
angularangular-httpclient

How to use returned value/s in Angular 5?


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?


Solution

  • 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...");
      }
    );