angular2-rc4 http.post不适用于chrome和IE

时间:2016-07-13 12:27:57

标签: angular angular2-routing

我已经编写了一个服务来在@ angular2-rc1中执行http post操作。更新到rc4之后,它停止使用chrome,即使它在firefox中工作 当我尝试通过post请求发送数据时,它在请求中显示firebug中的数据(检查chrome的元素),但服务器正在获取空字符串。 以下是代码:

import {Injectable} from '@angular/core';
import {Http, Response, Headers, RequestOptions, BaseRequestOptions} from "@angular/http";
import {Observable} from 'rxjs/Observable';
import 'rxjs/Rx';
import 'rxjs/add/operator/map'

@Injectable()
export class HttpService {
    constructor(private http: Http) {
    }

    login(url:string, data: string) {
        let headers = new Headers({'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8'});
        let options = new RequestOptions({headers: headers});
        return this.http.post(url, data, options);
    }

}

用于调用此登录方法的代码是:

this._httpService.login('rest/j_spring_security_check', 'j_username=user&j_password=pass').subscribe(
                data => this.authenticationSuccess(data),
                error => this.authenticationFailure(error)
            )

当我尝试通过firefox登录时,服务器正确获取用户名和密码,而服务器获取空字符串,如果通过chrome或ie完成相同的操作。 请帮忙。

1 个答案:

答案 0 :(得分:0)

您可以尝试使用RC4直接使用FormData对象:

login(url:string, data: string) {
  var body = new FormData();
  body.append('j_username', data.user);
  body.append('j_password', data.pass);

  return this.http.post(url, body);
}

或URLSearchParams类:

login(url:string, data: string) {
  var body = new URLSearchParams();
  body.set('j_username', data.user);
  body.set('j_password', data.pass);

  return this.http.post(url, body);
}

以这种方式调用login方法:

httpService.login('rest/j_spring_security_check', {
  user: 'user', pass: 'pass').subscribe(...);