angular2 http POST数据对象问题

时间:2016-03-31 17:56:49

标签: angular

我一直在努力使用Typescript / angular2通过http.post将对象传递给Web服务。

以下是我尝试的路径,但没有一个能够正常工作。

我的组件(在TS中):

export class DataFormComponent {

    newPerson: any;
    errorMessage: any;

    constructor(private _appServices: AppServices){}

    data:any = {"Login":"jsmith","TKID":"4000","FirstName":"john","LastName":"smith","FullName":"Smith, John","Email":"jsmith@gmail.com","ShortTitle":"Library Specialist","Extension":"5000","JobTitle":"Librarian","OfficeFloor":"33","Department":"Library","DepartmentCode":"LIB"};

    saveForm(){
        this._appServices.saveData(this.data)
            .subscribe(
                (result: any) => {
                    this.newPerson = result;
                }, (error) => {
                    // show error message
                    this.errorMessage = <any>error;
                }
            );
    }
}

我的打字稿服务:

saveData(data: any): Observable<any> {
        // let v.s. var, let(block scope) has smaller scope than var(function scope).

        let _url = 'webservices/wsServices.asmx/SaveData';

        let body = JSON.stringify({data});
        alert(body);
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });

        return this.http.post(_url, body, options)
            .map(response => <any> response.json())
            .catch(this.handleError);

    }

我的网络服务:(。Net)

[WebMethod]
        [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
        public void SaveData(string dataobject)
        {
            ...
        }

我总是得到的错误:

Response {_body: "{"Message":"No parameterless constructor defined f…,"ExceptionType":"System.MissingMethodException"}", status: 500, statusText: "Ok",...

所以我试着用我的老把戏。在Angular1中,我一直使用$ .param和JSON.stringify来转换数据对象并将其传递给我的Web服务。

this.saveData = function (oData) {

       var input = $.param({ myDataParam: JSON.stringify(oData) });

       return $http({
                method: 'POST',
                url: 'wsServices/wsProcess.asmx/SaveData',
                data: input,
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
            });
  };

我想知道是否有任何类似的方法/服务可用于Angular2 / Typescript。

1 个答案:

答案 0 :(得分:0)

感谢JB Nizet。问题似乎来自我的网络服务。

我将参数类型从字符串更改为对象。然后它开始工作!

$scope.selected = false;
$scope.add = function(price) {
    //If item is currently selected, subtract price
    if ($scope.selected) $scope.total_price -= price;
    //If item is currently NOT selected, add price
    else $scope.total_price += price;
    $scope.selected = !$scope.selected;
};