Calling Http.post does not trigger a post in angular 6
Asked Answered
R

1

8

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 !

Rob answered 7/7, 2018 at 16:13 Comment(8)
Are you subscribing to the Observable in your component?Attention
can you post the function where you call login?Fawnfawna
Login is callled properly and the parameters are passed correctly.Forestaysail
@PierrickMartellière Please add the code anyway. It allows us to check things like whether you've subscribed correctly.Attention
I added it anyway.Forestaysail
As suspected, you're not subscribed to the observable, so the HTTP call will never be madeAttention
@Attention thanks, how and where am I supposed to subscribe this Observable ?Forestaysail
Possible duplicate of Angular http.post without .subscribe callbackPolemoniaceous
A
31

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 
});
Attention answered 7/7, 2018 at 16:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.