简体   繁体   中英

POST form Angular2

I'm trying to execute a login form with Angular2 with NodeJS API as a backend server.

I cant't post any request to the API. Here it's my front code example:

private authenticate_url = "Server_URL:PORT/authenticate";
login(username: string, password: string): Observable<User> {
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });
    console.log("Username : "+username+" Password : "+password);
    return this.http.post(this.authenticate_url, { username, password }, options)
                .map(this.extractData)
                .catch(this.handleError)
}

Either when I'm checking network activity, no POST request was executed.

You need to use .subscribe() method of RxJS in order to actually execute the query, so you need to write it like this:

return this.http.post(this.authenticate_url, { username, password }, options)
                .map(this.extractData)
                .catch(this.handleError)
                .subscribe((queryResult) => {console.log(queryResult)})

Or you can do it outside your function like:

login("baksdasd", "asfasfasdf").subscribe((queryResult) => {console.log(queryResult)})

You also need to import the operators that you use:

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

Here you have a detailed tutorial to solve any other problem that you may have: https://scotch.io/tutorials/angular-2-http-requests-with-observables

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM