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

做~自己de王妃 提交于 2020-01-21 02:15:12

问题


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 !


回答1:


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 
});


来源:https://stackoverflow.com/questions/51224862/calling-http-post-does-not-trigger-a-post-in-angular-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!