So, I am an Ionic and Angular newbie to making mobile apps. However, I have a basic login form, and a login button which successfully calls a controller. The controller looks like:
angular.module('starter.controllers', [])
.controller('LoginCtrl', function($scope, LoginService, $ionicPopup, $state) {
$scope.data = {};
$scope.login = function() {
LoginService.loginUser($scope.data.username, $scope.data.password)
.success(function(data) {
// $state.go('tab.dash');
var alertPopup = $ionicPopup.alert({
title: 'Login HERE!',
template: 'HERE: your credentials!'
});
}).error(function(data) {
var alertPopup = $ionicPopup.alert({
title: 'Login failed!',
template: 'Please check your credentials!'
});
});
}
});
This now calls a service which looks like:
angular.module('starter.services', [])
.service('LoginService', function($http,$q) {
return {
loginUser : function(name, pw) {
console.log('username=' + name + ', password=' + pw);
var deferred = $q.defer();
var promise = deferred.promise;
var url = 'https://myURL/myapi/authenticate?username=' + name + '&password=' + pw;
console.log('url=' + url);
$http.get(url)
.success(function(data) {
console.log("success: data=" +data);
deferred.resolve(data);
})
.error(function() {
console.log("error");
deferred.reject("Failed to authenticate");
});
// Return the promise to the controller
promise.success = function(fn) {
promise.then(fn);
return promise;
}
promise.error = function(fn) {
promise.then(null, fn);
return promise;
}
return promise;
}
}
})
The URL I have gets built correctly, it calls the RESTful api correctly. In the event of a successful login, I get a token id as a single string. In the event of an unsuccessful login, I get an single line as an error message.
I did read that a GET restful web call expects an array of data. I can see in the controller.js that: String data = {};
The real error message I am getting is that .success in the controller is not mapped to getting a String, but an array instead.
If anyone can help me out with whether I can make my data an array, or if I can add a new .success and .error with a single string, that would be great.
Thanks!
You've way over-complicated your promise handling AFAICT. I'm not even sure what you're trying to do with all those success and error functions. You can just have:
angular.module('starter.services', [])
.service('LoginService', function($http,$q) {
return {
loginUser : function(name, pw) {
console.log('username=' + name + ', password=' + pw);
var url = 'https://myURL/myapi/authenticate?username=' + name + '&password=' + pw;
console.log('url=' + url);
return $http.get(url);
}
}
})