the title to this is a bit ambiguous I know, but I couldn't think of what to call it :)
Hopefully this description will help.
I have this current "service" which looks like this:
.factory('MoltinApi', ['$cookies', '$q', '$resource', '$http', 'moltin_options', function ($cookies, $q, $resource, $http, options) {
var api = $resource(options.url + options.version + '/:path', {
path: '#path'
});
var authenticate = function () {
if (!options.publicKey)
return;
var deferred = $q.defer();
//var authData = angular.fromJson($cookies.authData);
var authData = false;
if (!authData) {
console.log('from api');
var request = {
method: 'POST',
url: options.url + 'oauth/access_token',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: "grant_type=implicit&client_id=" + options.publicKey
};
deferred.resolve($http(request).success(function (response) {
$cookies.authData = angular.toJson(response);
setHeaders(response.access_token);
}));
} else {
console.log('from cookie');
deferred.resolve(setHeaders(authData.access_token));
}
return deferred.promise;
};
var setHeaders = function (token) {
$http.defaults.headers.common['Authorization'] = 'Bearer ' + token;
}
return authenticate().then(function (response) {
return api;
});
}]);
As you can see, when we authenticate, we then return the api function.
I have decided that using $resource isn't working as good as I had hoped, so I have now tried to change the service to this:
.factory('MoltinApi', ['$cookies', '$q', '$http', 'moltin_options', function ($cookies, $q, $resource, $http, options) {
// Private variables
var headers;
// Build request call
var buildRequest = function (path, method, data) {
var request = {
method: method,
url: options.url + options.version + path,
data: data
};
console.log(headers);
if (headers) {
angular.extend(request, headers)
}
return $http.request(request);
}
// GET
var $get = function (path) {
var request = buildRequest(path, 'GET')
return $http.request(request);
}
// POST
var $post = function (path, data) {
var request = buildRequest(path, 'POST', data)
return $http.request(request);
}
// PUT
var $update = function (path, data) {
var request = buildRequest(path, 'PUT', data)
return $http.request(request);
}
// DELETE
var $delete = function (path) {
var request = buildRequest(path, 'DELETE')
return $http.request(request);
}
// authentication
var authenticate = function () {
if (!options.publicKey)
return;
var deferred = $q.defer();
//var authData = angular.fromJson($cookies.authData);
var authData = false;
if (!authData) {
console.log('from api');
var request = {
method: 'POST',
url: options.url + 'oauth/access_token',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: 'grant_type=implicit&client_id=' + options.publicKey
};
deferred.resolve($http(request).success(function (response) {
$cookies.authData = angular.toJson(response);
headers = { headers: { 'Authorization': 'Bearer ' + response.access_token } }
}));
} else {
console.log('from cookie');
deferred.resolve(
headers = { headers: { 'Authorization': 'Bearer ' + authData.access_token } }
);
}
return deferred.promise;
};
return authenticate().then(function (response) {
// Need to return $post, $get, $update and $delete
});
}]);
But I am at a loss on how to return my methods after we have athenticated...
Can someone help me out?
you need to wrap all the methods into an object, and return the object. Try:
var api = {};
...
api.$get = function (path) {
...
api.$post = function (path, data) {
...
//etc
return authenticate().then(function (response) {
return api;
});
Related
I have an interceptor that handles all my requests on my controllers. I have a back-end web API that implements a refresh token but when I try to refresh my token and continue with the request being made I get "Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. The response had HTTP status code 400." And the token request gives me {"error":"invalid_clientId","error_description":"ClientId should be sent."}
Interceptor:
var appInterceptors = angular.module("auth-Interceptor", ["ngRoute", "angular-loading-bar"]);
/* ==== Bearer token headers configuration ==== */
appInterceptors.factory("authentication-interceptor", ["$q", "$injector", "$rootScope", "$location", "cfpLoadingBar", function ($q, $injector, $rootScope, $location, cfpLoadingBar) {
var inFlightAuthRequest = null;
var deferred = $q.defer();
return {
// On request success
request: function (config) {
config.headers = config.headers || {};
if ($rootScope.globals.accessToken != null) {
config.headers.Authorization = 'Bearer ' + $rootScope.globals.accessToken;
}
// Return the config or wrap it in a promise if blank.
return config || $q.when(config);
},
requestError: function (rejection) {
debugger; //return debugger for more info
return rejection;
},
responseError: function (rejection) {
debugger;
if (rejection.status === 401) {
var refreshToken = window.localStorage.getItem("refreshToken"); //log the user in if there is an refresh token
$injector.get("$http").post(
$rootScope.globals.apiPath + "/accessControl/token",
{ client_id: "id", grant_type: "refresh_token", refresh_token: refreshToken },
{ 'Content-Type': 'application/x-www-form-urlencoded' }
)
.then(function (data) {
inflightAuthRequest = null;
if (data.access_token != undefined && data.refresh_token != undefined) {
window.localStorage.setItem("refreshToken", data.refresh_token);
window.localStorage.setItem("accessToken", data.access_token);
window.localStorage.setItem("rememberMe", true);
window.localStorage.setItem("time_expires_in", data.expires_in);
$injector.get("$http")(rejection.config).then(function (resp) {
deferred.resolve(resp);
}, function (resp) {
deferred.reject();
});
} else {
deferred.reject();
}
return $q.reject(rejection);
}, function (response) {
deferred.reject();
authService.clear();
$injector.get("$state").go('/login');
return;
});
return deferred.promise;
}
}
};
}]);
appInterceptors.config(["$httpProvider", function ($httpProvider) {
$httpProvider.interceptors.push("authentication-interceptor");
}]);
Service:
jobManagerApp.factory("authenticationService", ["$rootScope", "$http", "$location", function ($rootScope, $http, $location) {
return {
Login: function (username, password) {
return $http({
url: $rootScope.globals.apiPath + "/accessControl/token",
method: 'POST',
data: "userName=" + encodeURIComponent(username) +
"&password=" + encodeURIComponent(password) +
"&Scope=" + "website" +
"&grant_type=password" +
"&client_id=id",
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
},
RefreshToken: function (refreshtoken) {
return $http({
url: $rootScope.globals.apiPath + "/accessControl/token",
method: 'POST',
data: "client_id=" +
"&grant_type=refresh_token" +
"&refresh_token=" + refreshtoken,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
},
LogOut: function () {
return $http({
url: $rootScope.globals.apiPath + "/accessControl/logout",
method: "POST"
});
},
DoLogin: function (data, rememberMe) {
//save the tokens
if (rememberMe == true) {
window.localStorage.setItem("refreshToken", data.refresh_token);
window.localStorage.setItem("accessToken", data.access_token);
window.localStorage.setItem("rememberMe", true);
} else {
window.localStorage.removeItem("refreshToken");
window.localStorage.removeItem("accessToken");
}
//set the global values for user
$rootScope.globals.accessToken = data.access_token;
$rootScope.globals.refreshToken = data.refresh_token;
//hide the menu items for which the users does not have access rights
$rootScope.HideMenuItems();
//navigate to the page where the user originally wanted to go (returnLocation) or to the default page
var gotoLocation = $rootScope.globals.returnToLocation;
if (gotoLocation != "") {
$location.path(gotoLocation);
$rootScope.globals.returnToLocation = "";
} else {
//go to default page
$location.path("/home");
}
//set the logged in value only after the navigation has taken place as it is linked to the ng-show/hide of the toolbar and menu
$rootScope.globals.isLoggedIn = true;
}
};
}]);
Login:
jobManagerApp.controller("loginController", ["$scope", "$rootScope", "$location", "authenticationService", function ($scope, $rootScope, $location, authenticationService) {
$scope.LoginButtonDisabled = false;
$scope.LogonName = null;
$scope.Password = null;
$scope.Error = "";
$scope.Version = ($rootScope.globals.version.indexOf("-") == -1) ? $rootScope.globals.version : $rootScope.globals.version.substring(0, $rootScope.globals.version.indexOf("-"));
$scope.Login = function () {
$scope.LoginButtonDisabled = true;
if ($scope.LogonName !== null && $scope.Password !== null) {
//attempt login
authenticationService.Login($scope.LogonName, $scope.Password)
.success(function (data) {
$scope.LoginButtonDisabled = false;
if (data.access_token != undefined) {
//Time Expires
window.localStorage.setItem("time_expires_in", data.expires_in);
//Time user logged in
window.localStorage.setItem("time_logged_in", new Date().getTime());
//do the actual login
authenticationService.DoLogin(data, $scope.RememberMe);
}
else if (data.error_description != undefined) {
$scope.Error = data.error_description;
}
else {
$scope.Error = "Unexpected error occurred!";
}
})
.error(function (data, status, headers, config) {
$rootScope.globals.accessToken = null;
window.localStorage.removeItem("accessToken");
window.localStorage.removeItem("refreshToken");
$scope.LoginButtonDisabled = false;
});
} else {
$scope.Error = "Enter a username and password!";
$scope.LoginButtonDisabled = false;
}
};
var accessToken = window.localStorage.getItem("accessToken"); //log the user in if there is an access token
var refreshToken = window.localStorage.getItem("refreshToken"); //log the user in if there is an refresh token
var time_expires = window.localStorage.getItem("time_expires_in"); //Time token expires
var time_logged_in = window.localStorage.getItem("time_logged_in"); //Time user logged in
var time = new Date().getTime(); //CurrentTime
var tokenExpired; //variable to be used to setExpired
if (((time / 1000) - (time_logged_in / 1000)) >= time_expires) {
tokenExpired = true;
} else {
tokenExpired = false;
}
//Log test
console.log("Time left: " + (time_expires - ((time / 1000) - (time_logged_in / 1000))));
console.log(refreshToken);
//login
if (accessToken != null && tokenExpired == false && refreshToken != null) {
$rootScope.globals.accessToken = accessToken; //set this for the auth-interceptor to do its work
$rootScope.globals.showLoading = true;
$rootScope.globals.showLoading = false;
var data = {
access_token: accessToken,
expires_in: time_expires,
refresh_token: refreshToken
};
authenticationService.DoLogin(data, true);
//authenticationService.GetAuthenticationProperties().success(function (data) {
// $rootScope.globals.showLoading = false;
// data.access_token = accessToken;
// authenticationService.DoLogin(data, true);
//}).error(function () {
// $rootScope.globals.showLoading = false;
//});
} else if (refreshToken != null) {
//request a new access token
authenticationService.RefreshToken(refreshToken)
.success(function (data) {
if (data.access_token != undefined && data.refresh_token != undefined) {
$rootScope.globals.accessToken = data.access_token; //set this for the auth-interceptor to do its work
$rootScope.globals.refreshToken = data.refresh_token //Set the new refresh token
$rootScope.globals.showLoading = true;
$rootScope.globals.showLoading = false;
var data = {
access_token: data.access_token,
refresh_token: data.refresh_token,
expires_in: data.expires_in
};
//Renew the time logged in and the time time_expires
//Time Expires
window.localStorage.setItem("time_expires_in", data.expires_in);
//Time user logged in
window.localStorage.setItem("time_logged_in", new Date().getTime());
//Set the access token
tokenExpired = false //renew to false;
authenticationService.DoLogin(data, true);
}
})
.error(function (data, status, headers, config) {
$rootScope.globals.accessToken = null;
window.localStorage.removeItem("accessToken");
window.localStorage.removeItem("refreshToken");
$scope.LoginButtonDisabled = false;
});
}
}]);
Any help would much be appreciated.
I have managed to fix my own problem, on the interceptor I injected the authService functions and reset the localstorage access, I then added and "ALLOW OPTION" for option requests to be resolved on my web API:
Interceptor
appInterceptors.factory("authentication-interceptor", ["$q", "$injector", "$rootScope", "$location", "cfpLoadingBar", function ($q, $injector, $rootScope, $location, cfpLoadingBar) {
return {
// On request success
request: function (config) {
config.headers = config.headers || {};
if ($rootScope.globals.accessToken != null) {
config.headers.Authorization = 'Bearer ' + $rootScope.globals.accessToken;
}
// Return the config or wrap it in a promise if blank.
return config || $q.when(config);
},
requestError: function (rejection) {
debugger;
return rejection;
},
responseError: function (response) {
// error - was it 401 or something else?
if (response.status === 401) {
var deferred = $q.defer(); // defer until we can re-request a new token
var accessToken = window.localStorage.getItem("accessToken");
var refreshtoken = window.localStorage.getItem("refreshToken");
// Get a new token... (cannot inject $http directly as will cause a circular ref)
$injector.get("authenticationService").RefreshToken(refreshtoken).then(function (loginResponse) {
if (loginResponse) {
console.log(loginResponse);
$rootScope.globals.accessToken = loginResponse.data.access_token; // we have a new acces token - set at $rootScope
$rootScope.globals.refreshToken = loginResponse.data.refresh_token; // we have a new refresh token - set at $rootScope
//Update the headers
window.localStorage.setItem("accessToken", loginResponse.data.access_token);
window.localStorage.setItem("refreshToken", loginResponse.data.refresh_token);
window.localStorage.setItem("rememberMe", true);
//Time Expires
window.localStorage.setItem("time_expires_in", loginResponse.data.expires_in);
//Time user logged in
window.localStorage.setItem("time_logged_in", new Date().getTime());
// now let's retry the original request - transformRequest in .run() below will add the new OAuth token
$injector.get("authenticationService").ResolveDeferred(response.config).then(function (defResp) {
// we have a successful response - resolve it using deferred
deferred.resolve(defResp);
}, function (defResp) {
deferred.reject(); // something went wrong
});
} else {
deferred.reject(); // login.json didn't give us data
}
}, function (response) {
deferred.reject(); // token retry failed, redirect so user can login again
$location.path('/login');
return;
});
return deferred.promise; // return the deferred promise
}
return $q.reject(response); // not a recoverable error
}
};
}]);
AuthenticationService
RefreshToken: function (refreshtoken) {
return $http({
url: $rootScope.globals.apiPath + "/accessControl/token",
method: 'POST',
datatype: 'jsonp',
data: "client_id=id" +
"&grant_type=refresh_token" +
"&refresh_token=" + refreshtoken,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
},
LogOut: function () {
return $http({
url: $rootScope.apiPath + "/acess/logout",
method: "POST"
});
},
ResolveDeferred: function (config) {
return $http(config);
},
API
public override Task MatchEndpoint(OAuthMatchEndpointContext context)
{
if (context.IsTokenEndpoint && context.Request.Method == "OPTIONS")
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Headers", new[] { "authorization" });
context.RequestCompleted();
return Task.FromResult(0);
}
return base.MatchEndpoint(context);
}
I am using AngularJs and backend CodeIgniter REST API .Here is the sample of code
data.js
`
app.factory("Data", ['$http', 'toaster','$log',
function ($http, toaster,$log) {
// This service connects to our REST API
var serviceBase = 'link';
var obj = {};
obj.toast = function (data) {
toaster.pop(data.status, "", data.message, 10000, 'trustedHtml');
}
obj.get = function (q) {
return $http.get(serviceBase + q).then(function (results) {
return results.data;
});
};
obj.post = function (q, object) {
//$log.log(object.customer);
$http({
method: 'POST',
url: serviceBase + q,
headers: {
Accept: "application/json",
"REST-API-KEY": "key"
},
data: object.customer
})
.then(function (results) {
$log.log(results);
return results.data;
});
};
obj.put = function (q, object) {
return $http.put(serviceBase + q, object).then(function (results) {
return results.data;
});
};
obj.delete = function (q) {
return $http.delete(serviceBase + q).then(function (results) {
return results.data;
});
};
return obj;
}]);
authctrl.js
app.controller('authCtrl', function ($scope, $rootScope, $routeParams, $location, $http, Data,sData) {
//initially set those objects to null to avoid undefined error
$scope.login = {};
$scope.signup = {};
$scope.doLogin = function (customer) {
Data.post('login', {
customer: customer
}).then(function (results) {
Data.toast(results);
if (results.status == "success") {
$location.path('dashboard');
}
});
};
$scope.signup = {email:'',password:'',name:'',phone:'',address:''};
$scope.signUp = function (customer) {
sData.post('signUp', {
customer: customer
}).then(function (results) {
Data.toast(results);
if (results.status == "success") {
$location.path('dashboard');
}
});
};
$scope.logout = function () {
Data.get('logout').then(function (results) {
Data.toast(results);
$location.path('login');
});
}
});
It is having an error which is
TypeError: Cannot read property 'then' of undefined
at h.$scope.doLogin (authCtrl.js:8)
at $a.functionCall (angular.min.js:172)
at angular.min.js:189
at h.a.$get.h.$eval (angular.min.js:108)
at h.a.$get.h.$apply (angular.min.js:109)
at HTMLButtonElement. (angular.min.js:189)
at angular.min.js:31
at q (angular.min.js:7)
at HTMLButtonElement.c (angular.min.js:31)
And also as you can see i am using single post method for both login and signUp function .So what i want to make it separate function like
For Login
obj.post = function (q, object) {
//$log.log(object.customer);
$http({
method: 'POST',
url: serviceBase + q,
headers: {
Accept: "application/json",
"REST-API-KEY": "3e9aba65f0701f5e7c1c8a0c7315039e"
},
data: object.customer
})
.then(function (results) {
$log.log(results);
return results.data;
});
};
For Sign up
obj.post = function (q, object) {
//$log.log(object.customer);
$http({
method: 'POST',
url: serviceBase + q,
headers: {
Accept: "application/json",
"REST-API-KEY": "3e9aba65f0701f5e7c1c8a0c7315039e"
},
data: object.customer
})
.then(function (results) {
$log.log(results);
return results.data;
});
};
How to write it in angularJs?
because you are returning nothing from Data.post, instead of returning the promise .
i.e. change your Data.post to
obj.post = function (q, object) {
//$log.log(object.customer);
return $http({
method: 'POST',
url: serviceBase + q,
headers: {
Accept: "application/json",
"REST-API-KEY": "key"
},
data: object.customer
});
};
This is my angularJS service and controller.
sampleApp.factory('BrandService', function($http, $q) {
var BrandService = {};
var BrandList = [];
BrandService.GetBrands = function() {
var Info = {};
Info.Action = "GET";
Info = JSON.stringify (Info);
var req = {
url: BrandURL,
method: 'POST',
headers: { 'Content-Type': 'application/json'},
data: Info
};
if ( BrandList.length == 0 )
{
$http(req)
.success(function(response) {
BrandList = response.data
alert ('Brand Fetching is successful');
return response.data;
})
.error(function (data, status, headers, config) {
alert ('Brand Fetching Error');
alert (status);
alert (data);
});
}
else
{
var deferred = $q.defer();
deferred.resolve(BrandList);
return deferred.promise;
}
}
return BrandService;
});
sampleApp.controller('BrandController', ['$scope', 'BrandService', function ($scope, BrandService){
$scope.Brands = [];
$scope.GetBrands = function() {
BrandService.GetBrands().then(function(data) {
$scope.Brands = data;
});
};
$scope.GetBrands();
}]);
When controller is loading I m seeing the following error.
Cannot read property 'then' of undefined
at l.$scope.GetBrands (Controllers.js:337)
Can please someone help me what i m doing wrong?
You are not returning promise in case of HTTP request when data is not yet cached.
Correct code would be:
sampleApp.factory('BrandService', function($http, $q) {
var BrandService = {};
var BrandList = [];
BrandService.GetBrands = function() {
var req = {
url: BrandURL,
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
data: JSON.stringify({Action: 'GET'})
};
if (BrandList.length) {
return $q.when(BrandList);
}
return $http(req)
.success(function(response) {
BrandList = response.data
alert('Brand Fetching is successful');
return response.data;
})
.error(function(data, status, headers, config) {
alert('Brand Fetching Error');
alert(status);
alert(data);
});
}
return BrandService;
});
Also you don't need to create dummy deferred object, you can return resolved promise with $q.when.
How to send __RequestVerificationToken when using $http angular?
Automatically add __RequestVerificationToken to data in posted data.
app.factory('LoginRepository', function ($http) {
return {
Login: function (lg) {
var req = {
method: 'POST',
url: '/Account/Login',
data: {
Username: lg.Username,
Password: lg.Username,
RememberMe: lg.Username,
},
}
return $http(req);
}
};
});
I assume that you want to add __RequestVerificationToken into the header of request ? If yes then you can use interceptors
app.config(function ($httpProvider) {
$httpProvider.interceptors.push('interceptorService');
});
InterceptorService itself will be a factory/service :
app.factory('InterceptorService ', ['localStorageService', function (localStorageService) {
var authInterceptorServiceFactory = {};
var _request = function (config) {
config.headers = config.headers || {};
var authData = localStorageService.get('token');
if (authData) {
config.headers.Authorization = 'Bearer ' + authData.token;
}
return config;
}}
I have Employee controller which is having property Id, Name , Specification. I have made one Employee service which is having ajax call and get employee list. But every time getting '' in User.
When i debug the code i found that it call success first and then it goes for Ajax call.
When i do ajax call without service it works fine.
angular.module('EmployeeServiceModule', [])
.service('EmployeeSer', ['$http',function ($http) {
this.Users = '';
this.errors = '';
this.SearchEmployee = function () {
// Ajax call
$http({
method: 'GET',
url: '/Home/GetEmployeeList',
params: { filterData: 'Test' },
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(onSuccess, onError);
var onSuccess = function (response) {
this.userUsers = response.data;
this.errors = '';
};
var onError = function (reason) {
this.userUsers = reason;
this.errors = "Error in retrieving data.";
};
return this.Users;
}
}]);
angular.module('Employee', ['EmployeeServiceModule'])
.controller('EmployeeController', ['EmployeeSer', '$scope', '$http', function (EmployeeSer, $scope, $http) {
this.Id = '';
this.name = '';
this.expertise = '';
$scope.repoSortOrder = 'id';
$scope.filterField = '';
// Call to service
this.GetAllEmployee = function () {
// Initiates the AJAX call
$scope.User = EmployeeSer.SearchEmployee();
// Returns the promise - Contains result once request completes
return true;
};
this.AddEmployee = function () {
var empData = {
Id: $("#txtId").val(),
Name: $("#txtName").val(),
Expertise: $("#expertise").val()
};
$http({
method: 'POST',
url: '/Home/Create',
params: JSON.stringify(empData),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(onSuccess, onError);
// Returns the promise - Contains result once request completes
return true;
};
var onSuccess = function (response) {
$scope.user = response.data;
$scope.error = '';
};
var onError = function (reason) {
$scope.error = "Error in retrieving data.";
};
}]);
It's because you are returning the users before the data is fetched from the server. Also it doesn't seem like you are assigning them correctly.
Here are two ways to solve the problem:
Firstly. You bind your controller user-data to the user-data in the service.
angular.module('EmployeeServiceModule', [])
.service('EmployeeSer', ['$http',function ($http) {
this.Users = '';
this.errors = '';
$http({
method: 'GET',
url: '/Home/GetEmployeeList',
params: { filterData: 'Test' },
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(onSuccess, onError);
var onSuccess = function (response) {
this.Users = response.data;
this.errors = '';
};
var onError = function (reason) {
this.users = null;
this.errors = "Error in retrieving data.";
};
}
}]);
angular.module('Employee', ['EmployeeServiceModule'])
.controller('EmployeeController', ['EmployeeSer', '$scope', '$http', function (EmployeeSer, $scope, $http) {
this.users = EmployeeSer.users;
EmployeeSer.SearchEmployee();
}]);
And the second way would be to return the promise in the service and unwrap it in the controller.
angular.module('EmployeeServiceModule', [])
.service('EmployeeSer', ['$http',function ($http) {
this.SearchEmployee = function () {
return $http({
method: 'GET',
url: '/Home/GetEmployeeList',
params: { filterData: 'Test' },
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
}
}]);
angular.module('Employee', ['EmployeeServiceModule'])
.controller('EmployeeController', ['EmployeeSer', '$scope', '$http', function (EmployeeSer, $scope, $http) {
this.GetAllEmployee = function () {
EmployeeSer.SearchEmployee()
.then(onSuccess, onError)
};
var onSuccess = function (response) {
$scope.user = response.data;
$scope.error = '';
};
var onError = function (reason) {
$scope.error = "Error in retrieving data.";
};
}]);
OFF TOPIC
You should probably consider using ngModel instead of jQuery to get you data to the controller.
Not like this:
var empData = {
Id: $("#txtId").val(),
Name: $("#txtName").val(),
Expertise: $("#expertise").val()
};
// Here serverRequest is my service to make requests to the server
serverRequest.postReq = function(url, data, sucessCallback, errorCallback){
$http({
method: 'POST',
url: urlToBeUsed,
data:data,
headers : {'Content-Type': 'application/x-www-form-urlencoded'}})
.success(function(data, status, headers, config) {
sucessCallback(data);
})
.error(function(data, status, headers, config){
errorCallback(data);
})
}
// In the controller
serverRequest.postReq('urlToBeCalled', dataToBeSent, scope.successCb, scope.errorCb);
scope.successCb = function(data){
// functionality to be done
}
scope.errorCb = function(data){
// functionality to be done
}
Try it this way your problem might be solved
Promise must be unwrapped in your controller if you want to use it