In my Angular 1.x application I am doing following on a form submit.
$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');
}
}
What I am doing here is, getting the selected items from a checkbox list and save that list to database by calling backend service call. Now I need to convert this code to Angular 2.
TRIED
In my service.ts file I use following.
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());
}
Then I call this service as below in my interst.ts file.
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');
});
}
This gives following error on console log.
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
Any suggestions are highly appreciated