Here i need to search name in scroll,for that i send search data query string in get call but i need to that in post.
Here is my server and client controller route and service.Also here i handling search from server side.How to post data which user has been searched ,and pass that to client and server side.
client controller service:
'use strict';
angular.module('details').factory('DetailService', ['$resource',
function($resource) {
return $resource('details', {
},
searchUsers:{
method: 'GET',
}
});
}
]);
Angular controller:
$scope.searchServer = function(searchData){
DetailService.searchUsers({search:searchData},function(response){
}, function(error){
$scope.status = 'Unable to load customer data: ' + error.message;
});
}
my Server side controller:
exports.searchCust = function (req, res) {
var strWhere = {
corporateName: search
};
db.Customer.findAll({
where: [strWhere],
}).then(function (customers) {
if (!customers) {
return res.status(400).send({
message: 'Customer not found.'
});
} else {
res.jsonp(customers);
}
})
};
my server sideroute:
app.route('/details').all(customersPolicy.isAllowed)
.get(details.searchCust);
app.param('search', details.searchCust);
};
I didn't try it out in all details as it looks like it was copy and pasted together without reading the basics. However, if you want POST requests, you need to set them both in the node-code and the Angular code, see below. What's more, Angular doesn't use JSONP, it uses JSON, so you need to set that. In the searchUsers-resource-call you only implemented the error-branch, so the results would just vanish. You'll find them in $scope.searchResults now.
client controller service:
'use strict';
angular.module('details').factory('DetailService', ['$resource',
function($resource) {
return $resource('details', {},
searchUsers: {
method: 'POST',
}
});
}]);
Angular controller:
$scope.searchServer = function(searchData) {
DetailService.searchUsers({
search: searchData
}, function(response) {
$scope.status = "OK";
$scope.searchResults = response;
}, function(error) {
$scope.status = 'Unable to load customer data: ' + error.message;
});
}
my Server side controller
exports.searchCust = function(req, res) {
var strWhere = {
corporateName: search
};
db.Customer.findAll({
where: [strWhere],
}).then(function(customers) {
if (!customers) {
return res.status(400).send({
message: 'Customer not found.'
});
} else {
res.json(customers);
}
})
};
my server sideroute:
app.route('/details').all(customersPolicy.isAllowed)
.post(details.searchCust);
app.param('search', details.searchCust);
};
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 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 !
I create a simple single page application with angularJS and laravel , , the method get, delete and store created , now how create the update method in my code?
I use below link in my app
https://scotch.io/tutorials/create-a-laravel-and-angular-single-page-comment-application
var app = angular.module('app',['ui.bootstrap'],function($interpolateProvider) {
$interpolateProvider.startSymbol('<%');
$interpolateProvider.endSymbol('%>');
});
app.factory('Depot', function($http) {
return {
get : function() {
return $http.get('depots/depot');
},
save : function(commentData) {
return $http({
method: 'POST',
url: 'depots/depot',
headers: { 'Content-Type' : 'application/x-www-form-urlencoded' },
data: $.param(commentData)
});
},
destroy : function(depot_number) {
return $http.delete('depots/depot/' + depot_number);
}
}
});
app.controller('appCtrl', function($scope, $http, Depot) {
$scope.commentData = {};
$('#show_success').hide();
$('#show_remove').hide();
Depot.get()
.success(function(data) {
$scope.comments = data;
});
$scope.submitComment = function() {
Depot.save($scope.commentData)
.success(function(data) {
Depot.get()
.success(function(getData) {
$('#add_depot').hide();
$('#depot_name').val('');
$('#have_id').removeAttr('checked');
$('#show_success').show();
setTimeout(function() {
$('#show_success').hide();
},1500);
$scope.comments = getData;
});
})
.error(function(data) {
console.log(data);
});
};
$scope.deleteComment = function(id) {
Depot.destroy(id)
.success(function(data) {
Depot.get()
.success(function(getData) {
$('#show_remove').show();
setTimeout(function() {
$('#show_remove').hide();
},1500);
$scope.comments = getData;
});
});
};
});
You should read up on the documentation for ngResource. This is by far your best bet for a RESTful application.
I have answered another question a bit more detailed, perhaps it could help you too?
We really do need your endpoints / server-code to help you more.
I have the following:
Node/Express router:
var City = require('./models/city');
module.exports = function(app) {
app.get('/cities/:zip', function(req, res) {
console.log(req.params.zip);
var query = City.find({"zip" : req.params.zip})
query.exec(function(err, city) {
if (err)
res.send(err);
console.log(city);
res.json(city);
});
});
app.get('*', function(req, res) {
res.sendfile('./public/views/index.html'); // load our public/index.html file
});
};
Angular Service:
angular.module('CityService', []).factory('City', ['$http', function($http) {
return {
get : function(zip) {
var zip = zip.zip
return $http.get('/cities/' + zip);
}
}
}]);
Angular Controller:
angular.module('CityCtrl', []).controller('CityController', ['$scope', '$http', 'City', function($scope, $http, City){
$scope.update = function (zip) {
$scope.weather = City.get({zip : zip});
if(zip.length = 5){
$http.jsonp('http://api.openweathermap.org/data/2.5/weather?zip='+ zip +',us&callback=JSON_CALLBACK').success(function(data){
$scope.data=data;
console.log(data.name);
});
}
}
}]);
Everything seems to be working fine. However, when I try to log the $scope.weather I get the entire header. I've tried logging $scope.weather.name (I know it's there) and then it returns "undefined". When I check what the server is logging it appears to log the correct JSON response. Any idea of how to get the "name" field of the returned document?
Replace $scope.weather = City.get({zip : zip}); to City.get({zip : zip}).then(function(response){$scope.weather= response.data});
As we know $http return a promise object so you must have to resolve it. you are not resolving it in service so you have to set $scope.weather in then.
I'm trying to make a simple login function for my AngularJS application. I'm using Dream Factory for my backend server database and I can't seem to be able to create a session from my login-function.
This is the factory I have set up:
dfdevApp.factory('SessionService', function($resource, $q) {
var sessionResource = $resource('https://dsp-myusername.cloud.dreamfactory.com/rest/user/session', {},
{ update: { method: 'PUT' }, query: {method: 'GET', isArray: false} });
return {
create: function (user) {
var deferred = $q.defer();
sessionResource.save(user, function (result) {
deferred.resolve(result);
}, function (error) {
deferred.reject(error);
});
return deferred.promise;
}
}
});
And this is the code from my controller:
// $scope.ting = Liste.get()
$scope.user = {'email' : '', 'password': ''};
$scope.login = function() {
console.log(JSON.stringify($scope.user));
$scope.user = SessionService.create(JSON.stringify($scope.user), function(success) {
$rootScope.loggedIn = true;
$location.path('/');
}, function(error) {
$scope.loginError = true;
});
};
});
I get a 400 every time I try to post.
Your post should be like this one:
{"email":"you#youremail.com","password":"yourpassword"}
Also don't forget to include your app_name in the URL or as a header (in this case, call it X-DreamFactory-Application-Name).
You can find more info here:
http://blog.dreamfactory.com/blog/bid/326379/Getting-Started-with-the-DreamFactory-API
I also built an "SDK" which handles all this for you.
https://github.com/dreamfactorysoftware/javascript-sdk