Calling Http.post does not trigger a post in angular 6

Pierrick Martellière picture Pierrick Martellière · Jul 7, 2018 · Viewed 12.9k times · Source

I generated my entities components and services according to my model using this tool.

Everything worked fine, but I ran into a problem when trying to log a user in my API (that is functional).

The http.post() method is not triggered. I'm pretty new to angular and can't figure out what I am doing wrong.

Any help would be great!

Here's my login method from my UserService (the method is called properly, it's only the http.post() that's not working):

/**
 * Log a user by its credentials.
 */
login(username : string, password : string) : Observable<NmUser> {
    let body = JSON.stringify({
        'username': username,
        'password': password
    });
    console.log(body);
    return this.http.post(this.userUrl + 'login', body, httpOptions)
        .pipe(
            map(response => new NmUser(response)),
            catchError(this.handleError)
        );
} // sample method from angular doc
private handleError (error: HttpErrorResponse) {
    // TODO: seems we cannot use messageService from here...
    let errMsg = (error.message) ? error.message : 'Server error';
    console.error(errMsg);
    if (error.status === 401 ) {
        window.location.href = '/';
    }
    return Observable.throw(errMsg);
}

Here's the page that is calling the login function:

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { NmUserService } from '../../app/entities/nmUser/nmUser.service';

@Component({
  selector: 'page-login',
  templateUrl: 'login.html',
  providers: [NmUserService]
})
export class LoginPage {

  constructor(private navCtrl: NavController, private userService: NmUserService) {

  }

  login(username: string, password: string): void {
    this.userService.login(username, password);
  }

}

Thanks !

Answer

user184994 picture user184994 · Jul 7, 2018

The HTTP call will never be made unless you subscribe to the observable, which is done within the component like so:

this.userService.login(username, password).subscribe((result) => {
    // This code will be executed when the HTTP call returns successfully 
});