Angular 2:实现HTTP POST请求

Angular 2: Implementing HTTP POST Request

本文关键字:POST 请求 HTTP 实现 Angular      更新时间:2023-09-26

在我的Angular 1.x应用程序中,我正在表单提交中执行以下操作。

$scope.submit = function() {
    console.log('Saving Form Data..');
    $scope.selection_array = [];
    for ( var j = 0; j < $scope.checkboxlist.length; j++ ){
        if ($scope.checkboxlist[j].selected) {
            console.log($scope.checkboxlist[j]);
            $scope.selection_array.push($scope.checkboxlist[j].key);
        }
    }
    if ($scope.selection_array.length>0) {
        $http({
            method : 'POST',
            url : BASE_URL + '/user/selection',
            headers : {
                'Content-Type' : 'application/json'
            },
            params : {
                access_token : localStorage.getItem("access_token")
            },
            data : $scope.selection_array
        }).success(function(response) {
            console.log('response=>' + response);
            $window.alert('Your items have been saved successfully');
        }).error(function() {
            console.log('failure in updaing');
            $window.alert('Error saving items. Please try again');
        });
    } else {
        $window.alert('Please select one or more items');
    }
}

我在这里所做的是,从复选框列表中获取所选项目,并通过调用后端服务调用将该列表保存到数据库中。现在我需要将此代码转换为Angular 2。

尝试

在我的service.ts文件中,我使用以下内容。

saveUserInterests(selected_interests) {
    console.log(selected_interests);
    var headers = new Headers();
    headers.append('Content-Type', 'application/json');
    var params = new URLSearchParams();
    params.set('access_token', localStorage.getItem('access_token'));
    return this.http.post('http://localhost:8080/user/interests',
        JSON.stringify(selected_interests),
        {
            headers: headers,
            search: params
        }).map(res => res.json());
}

然后我在interst.ts文件中调用此服务,如下所示。

private selected_interests;
onSubmit() {
    console.log('Inside onsubmit');
    var selected_interests = [];
    for (var j = 0; j < this.interests.length; j++) {
        if (this.interests[j].selected) {
            console.log(this.interests[j]);
            selected_interests.push(this.interests[j].key);
        } else {
            console.log('else');
        }
    }
    this.selected_interests = selected_interests;
    console.log(this.selected_interests);

    this.dataService.saveUserInterests(this.selected_interests).subscribe(
        (res) => {
            console.log('response=>' + res);
            alert('Your items have been saved successfully');
        },
        (error) => {
            console.log('failure in updaing');
            alert('Error saving items. Please try again');
        });
}

这在控制台日志中给出以下错误。

Rx.js:10982 Uncaught EXCEPTION: Error during evaluation of "ngSubmit"
ORIGINAL EXCEPTION: TypeError: Cannot read property 'subscribe' of undefined
ORIGINAL STACKTRACE:
TypeError: Cannot read property 'subscribe' of undefined

任何建议都将受到高度赞赏

对于HTTP部分,以下是Angular2:中的操作方法

constructor(private http:Http, private window:Window) {
}
submit() {
  var selectionArray = (...)
  var headers = new Headers();
  headers.append('Content-Type' : 'application/json');
  var params = new URLSearchParams();
  params.set('access_token', localStorage.getItem('access_token'));
  this.http.post(BASE_URL + '/user/selection',
         JSON.stringify(selectionArray),
         {
           headers : headers,
           search: params
         }).map(res => res.json())
         .subscribe(
           (data) => {
             console.log('response=>' + response);
             this.window.alert('Your items have been saved successfully');
           },
           (error) => {
             console.log('failure in updaing');
             this.window.alert('Error saving items. Please try again');
         });
}

查看这些链接了解更多详细信息:

  • http://restlet.com/blog/2016/04/08/interacting-efficiently-with-a-restful-service-with-angular2-and-rxjs-part-1/
  • Angular2-如何将窗口注入Angular2服务