简体   繁体   English

POST表格Angular2

[英]POST form Angular2

I'm trying to execute a login form with Angular2 with NodeJS API as a backend server. 我正在尝试使用带有NodeJS API的Angular2作为后端服务器执行登录表单。

I cant't post any request to the API. 我无法向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. 在检查网络活动时,都没有执行POST请求。

You need to use .subscribe() method of RxJS in order to actually execute the query, so you need to write it like this: 您需要使用RxJS的.subscribe()方法才能实际执行查询,因此需要这样编写:

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 在这里,您有详细的教程来解决您可能遇到的任何其他问题: https : //scotch.io/tutorials/angular-2-http-requests-with-observables

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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