I am implementing Woo Commerce Rest API in my Angular/Ionic project on Cordova Platform. While I am making $http request to get product list or any other data, I am getting error Message. Here is my Service code:
angular.module('services.serverRepo', [])
.service("serverRepo",
['$q','$http','errorHandler','$ionicLoading',function($q,$http,errorHandler,$ionicLoading){
var baseUrl="www.abc.com/wc-api/";
var self=this;
this.products=function(){
var deff=$q.defer();
$http({
method:"GET",
url:baseUrl+"v3/products",
headers: {
"Content-Type":"application/JSON",
"oauth_consumer_key":"gjdfjkbgbdhh645h6bh456b45hbhbgdfhgbdfhgbdfhgbhgbdhfghhfhf",
"consumer_secret":"cs_97d74bbf5e9052ee053a05cbb1a53eec19c0847c"
}
}).then(function(objS){
alert('Success :- '+JSON.stringify(objS));
},function(objE){
alert('error:- '+objE);
errorHandler.serverErrorhandler(objE);
deff.reject("server Error");
});
return deff.promise;
};
}])
.service('errorHandler',['$q',function($q){
this.serverErrorhandler=function(error){
alert("ERROR ::"+JSON.stringify(error));
console.log("ERROR ::"+JSON.stringify(error));
};
}
])
and in my controller.js file code is:
$scope.rentaldeptt = function(){
//$ionicHistory.clearCache();
serverRepo.products().then(function(objS){
},function(err){
});
}
I am calling $scope.rentaldeptt on a button click. In response I am getting error message
{"data":{"errors":[{"code":"woocommerce_api_authentication_error","message":"oauth_timestamp parameter is missing"}]},"status":404,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"url":"www.abc.com/v3/products","headers":{"Accept":"application/json, text/plain, /"},"params":{"oauth_consumer_key":"gjdfjkbgbdhh645h6bh456b45hbhbgdfhgbdfhgbdfhgbhgbdhfghhfhf","consumer_secret":"cs_97d74bbf5e9052ee053a05cbb1a53eec19c0847c"}},"statusText":"Not Found"}
Any Idea what I am doing wrong?
Please try to following steps to resolve the isue,
Here, I have Created the service in angularjs to handle the calling of woocommerce api with the oauth,
angular.module('myapp.restservices', [])
.service("serverRepo",['$q','$http','errorHandler','$ionicLoading',function($q,$http,errorHandler,$ionicLoading){
var self=this;
//Request Url and method
var request = {
url: 'http://www.example.com/wc-api/v3/products',
method: 'GET'
};
//OAuth Protocol authentication parameters
var oauth = new OAuth({
consumer: {
//Consumer Public Key
public: 'ck_50xxxx',
//Consumer Secrete Key
secret: 'cs_b4xxxx'
},
//oauth1.0a protocol signature method
signature_method: 'HMAC-SHA1'
});
//Service Function to get products
this.products=function(){
$ionicLoading.show({
template: '<ion-spinner class="light"></ion-spinner>'
});
//OAuth Parameters to call woocommerce api
var oauth_data = {
oauth_consumer_key: oauth.consumer.public,
oauth_nonce: oauth.getNonce(),
oauth_signature_method: oauth.signature_method,
oauth_timestamp: oauth.getTimeStamp()
};
//Oauth signature
oauth_data.oauth_signature = oauthSignature.generate(request.method,request.url,oauth_data,oauth.consumer.secret );
console.log("Params : "+ JSON.stringify(oauth_data));
var deff=$q.defer();
$http({
method:"GET",
url:request.url,
headers: {
"Content-Type":"application/JSON",
},
params: oauth_data
}).then(function(objS){
$ionicLoading.hide();
alert('Success :- '+JSON.stringify(objS));
},function(objE){
$ionicLoading.hide();
alert('error:- '+JSON.stringify(objE));
errorHandler.serverErrorhandler(objE);
deff.reject("server Error");
});
return deff.promise;
};
}])
.service('errorHandler',['$q',function($q){
this.serverErrorhandler=function(error){
alert("ERROR ::"+JSON.stringify(error));
console.log("ERROR ::"+JSON.stringify(error));
};
}
])
Write controller to call the service function as like follows,
angular.module(myapp.categorycontrollers, [])
.controller('MainCtrl', function($scope,woocommerce) {
//Method to get all Products
$scope.getAllProducts = function(){
woocommerce.products().then(function(objS){
},function(err){
});
}
//calling to function
$scope.getAllProducts();
}
Hopes this will help you !
Related
Here is my controller and factory:
angular.module('app').controller('userCtrl', function($scope, User) {
$scope.users = [];
User.getUsers().then(function(response) {
$scope.users = response.data;
});
});
angular.module('app').factory('User', function($http) {
return $http.get('api-url-here').then(function(response) {
return response;
}, function(error) {
return error;
});
});
If there is no users, backend returns status code 404, or if there is internal server error, it returns status code 500. Otherwise it returns status
code 200 and users array.
In my AngularJS application, how I should show different messages depending on status code? I would like to have different messages on same status code in different pages.
// Defining your application module here in below.
var app = angular.module('app',['']);
// Using your application module defining your controller with dependency injection here in below.
app.controller('userCtrl',function($scope,User){
//Defining your getUser function using ECMA-5 syntax here in below.
$scope.getUser = function(){
// Using your factory named User calling the factory function getUsers().
User.getUsers().fetch({},function(respose){
if(respose.status == 200){ // using this way you could find the status of the response here.
var _data = angular.fromJson(respose.data);
$scope.users = _data;
}
}, function(respose){
$scope.users = [];
});
};
});
// Defining your factory service using your application module here in below.
app.factory('User',['$resource',$http, function($resource, $http){
var factory = {};
factoryName.getUsers = function(){
return $resource('api-url-here', {}, {
fetch: {
method: 'GET',
isArray: true,
header: {
'Content-Type' : 'application/json',
'Authorization' : Authorization
},
interceptor : {
response : function(data) {
return data;
}
}
}
})
};
return factory;
}]);
I am trying to get the model data in angular js ,but not able to get it . I printed the value on spring mvc side .The data is getting stored and is retrieved successfully with the given key.Can anyone tell me how can I achieve this .
My controller-
#RequestMapping(value = "/home.web", method = RequestMethod.GET, produces = {
"application/json" })
public ModelAndView getUSCity(#RequestParam ("statechoice") String statechoice) {
List<String> msa = new ArrayList<String>();
msa = msaService.getMsaCodes(statechoice);
/*ModelAndView model = new ModelAndView("Home");
model.addObject("cities",msa);
System.out.println(model.getModel().get("cities"));*/
//return msa;
return new ModelAndView("Home", "cities",msa);
}
My angular js -
function MyController($scope, $http) {
$scope.getPersonData = function() {
$http({
method : 'GET',
url : 'home.web'
}).success(function(data, status, headers, config) {
alert(data);
$scope.cities = data;
}).error(function(data, status, headers, config) {
console.log("error");
// called asynchronously if an error occurs
// or server returns response with an error status.
});
};
};
Split your code into controller and service because you should not do api calls from cotroller directly(best case). Services should be used. Controllers are only be used to controlling model to show it in the view.
myService.js
app.service('myService', ['$http', '$q', function($http, $q){
return {
getPersons: function(obj) {
var deferred = $q.defer();
$http({
method : obj.method,
url : obj.url
}).then(function(response) {
deferred.resolve(response);
}, function(error) {
alert(error);
deferred.reject(error);
// called asynchronously if an error occurs
// or server returns response with an error status.
});
return deferred.promise();
};
}
});
myController.js
function MyController('MyController', ['$scope', 'myService', function($scope, myService){
$scope.persons = [];
var obj = {method: 'GET', url: 'home.web'};
myService.getPersons(obj).then(function(response){
$scope.persons = response.data // or $scope.persons = response check yourself
}, function(error){
alert(error);
})
}]);
I am building an App with ionic and I want to handle the 500 internal server error which occurs in $http() AJAX call. Is it possible to create any interceptors to handle that?
here is my controller code:
.controller('RegistrationController',function($scope,$http){
$scope.doRegistration = function(){
$http({
method : "POST",
url : BASE_URL,
params : {
//sending the parameters as JSON
}
}).then(function successCallback(response){
if(response.status == 200)
//handling the response sent by server
},function errorCallback()});
};
});
if the user enters some invalid inputs and the server is unable to handle that it throws 500 Internal Server Error. When the AJAX call is made I am showing a spinner and when some server error occurs I should stop the AJAX call and stop the spinner and show some popup to user saying "Encountered server error".
'use strict';
angular.module('myApp').factory('MyService', function ($http, $q) {
var BASE_URL = 'some.url.com';
function register() {
var defer = $q.defer();
$http({method: "POST", url: BASE_URL, params: {}})
.then(function (response) {
defer.resolve(response.data);
})
.catch(function (reason) {
defer.resolve(reason);
});
return defer.promise;
}
return {
register: register
}
}).controller('MyController', function ($scope, MyService) {
MyService.register().then(function (response) {
// success
}).catch(function (reason) {
// err
if (reason.status === 500) {
// do something
$scope.spinner = false;
console.log('Encountered server error');
}
});
});
you can create interceptor as below -
app.factory('testResponseInterceptor', function ($q ,$rootScope,$location) {
return {
response: function (response) {
//correct response
return response;
},
responseError: function (response) {
//error in response
}
};
});
and configure it in your module -
app.config(function ($httpProvider) {
$httpProvider.interceptors.push('testResponseInterceptor');
});
I have an API I want to ensure that api has called mean get alert "api hit" else "api does not meet"
$http.post('v1/xyz/eeee res')
.success(function () {
////
})
Don't use the success method either way.Both methods have been deprecated.
The $http legacy promise methods success and error have been
deprecated. Use the standard then method instead. If
$httpProvider.useLegacyPromiseExtensions is set to false then these
methods will throw $http/legacy error.
Here is the shortcut method
$http.post('/someUrl', data, config).then(successCallback, errorCallback);
Here is a longer GET method sample
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Official Documentation
See Priya this is how it happens
Controller Coding :-
angular.module('myApp', [])
.controller('myCtrl', function ($scope, $http) {
$scope.hello = {name: "Boaz"};
$scope.newName = "";
$scope.sendPost = function() {
var data = $.param({
json: JSON.stringify({
name: $scope.newName
})
});
$http.post("/echo/json/", data).success(function(data, status) {
$scope.hello = data;
}).error(function(data, status, headers, config) {
// this isn't happening:
$scope.hello=data;
console.log('this is nt happening '+data.status);
})
}
})
Html Coding :-
<div ng-controller="myCtrl">
{{hello}}
<form ng-submit="sendPost()">
<input ng-model="newName"/>
<button type="submit">Send</button>
</form>
</div>
Finally You can see the Error result in My Fiddle :-
http://jsfiddle.net/bkUEu/2589/
with error status also
Hint :- Just replace post end-Point with : /echo/ Instead /echo/json/
Let Me Know the result ?
You can simply use console.log or alert like:
$http.post('v1/xyz/eeee res')
.success(function () {
console.log('api hit success')
})
.error(function () {
alert('api hit error')
})
Or you could use interceptors:
$httpProvider.interceptors.push(function() {
return {
'request': function(config) {
// statement to check if you are hitting your api
if (config.url.startsWith('/v1'))
alert('api hit')
}
};
});
var app = angular.module('app', ['ngResource']);
app.factory('UserFactory', function ($resource) {
return $resource('/com/vsoft/rest/users', {}, {
query: {
method: 'GET',
params: {},
isArray: false
}
});
});
app.controller('MyCtrl1', ['$scope', 'UserFactory', function ($scope, UserFactory) {
UserFactory.get({}, function (userFactory) {
$scope.firstname = userFactory.firstName;
$scope.lastname = userFactory.lastName;
});
});
}]);
i added above app in my html.But the app and angular-resource.js but my app.js is not exeuting.
If i removed ngResource module and $resource alert is coming.But if i used ngResource im nt getting alert.
Please help in this.If any one knows any Good Example to use Restful services with angularjs .Please Kindly send Url or code.
Please help me.
i called{{firstname}}
in my html but its not coming .
I use a service for handling RESTful messages
app.service('restService', function ($http, $log) {
'use strict';
var self = this;
var BASE_URL = "base/url/";
//First way how to do it
self.httpGet = function (url) {
$log.info("HTTP Get", url);
return postProcess($http({method: 'GET', url: BASE_URL + url}));
};
//Second way how to do it
self.httpPut = function (url, object) {
$log.info("HTTP Put", url);
return postProcess($http.put(BASE_URL + url, object));
};
self.httpPost = function (url, object) {
$log.info("HTTP Post", url);
return postProcess($http.post(BASE_URL + url, object));
};
self.httpDelete = function (url) {
$log.info("HTTP Delete", url);
return postProcess($http.delete(BASE_URL + url));
};
function postProcess(httpPromise) {
return httpPromise.then(function (response) {
if (response.status === 200) {
return response;
}
//Other than 200 is not ok (this is application specific)
failure(response);
}, function (response) {
failure(response);
});
}
/**
* Promise for failure HTTP codes
* #param response the HTTP response
*/
function failure(response) {
//Error handling
}
});
usable as
restService.httpGet("categories").then(function (response) {
categoryData = angular.fromJson(response.data);
//Broadcast an event to tell that the data is ready to be used
$rootScope.$broadcast("categoriesReady");
});