Prevent encode the rest call with post Method in Angular js - angularjs

I am using angular js and making a restcall. But I have one variable and this variable have some value when I put this variable in service then this variable value encoded in console.
REST CALL
var rep = "CX-0138_ES48A9CA";
Rh.all('example/demo/db ').post(" ",+JSON.stringify(rep)).then(function(resp)
{
})
then rep value is not exist in console url.
But when I removed +JSON.stringify then service(url) encoded.
var rep = "CX-0138_ES48A9CA";
Rh.all('example/demo/db ').post(" ",rep).then(function(resp)
{
})
Encoded service in console
How can set value of rep CX-0138_ES48A9CA in post method.

Try this:
Rh.all('example/demo/db ').post({rep: encodeUriComponent(rep)}).then(function(resp)
{
})

Related

Fetching data in the form of Array from Mongodb

I am using this function to get the values of all the input tags having name=type1[].
var values = $("input[name='type1[]']").map(function(){
return $(this).val();
}).get();
console.log(values);
When i console.log this value then i get an array in my console window and then i stores this variable inside my mongodb and when i later fetches it then it automatically gets converted into string.
What i wanna do is to get the variable exactly as an array form.
How can i do that?
Here is my Mongodb code and my ajax request
var template = new Temp({
input_text:req.body.input,
template_id:ss.user_id
})
$.ajax({
url:'./save',
type:'POST',
data:'input='+values+'&input1='+values1+'&count='+values1.length,
success:function(response){}
});
And i am using the middleware bodyparser.json() on my server page maybe because thats why it got converted into string.

Issues with single-requests in Restangular

I'm having a slight issue with my ability to consume REST data retrieved via Restangular in an angular controller. I have the following code which works fine for a list of accounts:
var baseAccounts = Restangular.all('accounts');
baseAccounts.getList().then(function(accounts) {
$scope.accounts = accounts;
});
This works perfectly for a list. I use similar syntax for a single account:
var baseAccount = Restangular.one('accounts');
baseAccount.getList(GUID).then(function(returnedAccount) {
$scope.currentAccount = returnedAccount;
});
I am using ng-repeat as the handling directive for my first request. I am attempting to bind with {{ account.name }} tags for the single request, but it does not seem to display any data despite the request being made properly. GUID is the parameter I must pass in to retrieve the relevant record.
I have combed through Restangular docs and it seems to me like I am composing my request properly. Any insight would be greatly appreciated.
EDIT: I've tried all of the solutions listed here to no avail. It would seem Restangular is submitting the correctly structured request, but when it returns it through my controller it shows up as just a request for a list of accounts. When the response is logged, it shows the same response as would be expected for a list of accounts. I do not believe this is a scoping issue as I have encapsulated my request in a way that should work to mitigate that. So, there seems to be a disconnect between Request -> Restangular object/promise that populates the request -> data-binding to the request. Restangular alternates between returning the array of accounts or undefined.
Have you looked at:
https://github.com/mgonto/restangular#using-values-directly-in-templates
Since Angular 1.2, Promise unwrapping in templates has been disabled by default and will be deprecated soon.
Try:
$scope.accounts = baseAccounts.getList().$object;
try:
var baseAccount = Restangular.one('accounts', GUID);
baseAccount.get().then(function(returnedAccount) {
$scope.currentAccount = returnedAccount;
});
The problem here is that it's expecting an array to be returned. I'm assuming that you are expecting an account object. Thus we need to use the get function, intead of getList()
The one() function has a second argument that accepts an id e.g. .one('users', 1). You can take a use of it.
CODE
var baseAccount = Restangular.one('accounts', 1); //1 would be account id
baseAccount.getList('account').then(function(returnedAccount) {
$scope.currentAccount = returnedAccount;
});
OR
var baseAccount = Restangular.one('accounts', 1); //1 would be account id
baseAccount.all('account').getList().then(function(returnedAccount) {
$scope.currentAccount = returnedAccount;
});
For more info take look at github issue
Hope this could help you, Thanks.

Encoding rest path variable in angularjs

I am having a peculiar issue.
I am calling a restful service with path param from angularjs controller/service.
Below is the url format
/payment/{id}/credit/{creditId}/fetch/options
Now, creditId has special charachters in it for eg 'abcd%xyz-433'
I am calling a service which makes a GET rest call as below in angualarjs controller
creditService.creditOption('abc','abcd%xyz-433').success(function(data, status) {
$log.log('log the status ' + status);
});
The service is as below
creditOption: function(id, creditId) {
return $http({
method: 'GET',
url: '/payment/'+id+'/credit/'+creditId+'/fetch/options'
});
}
The Restful service signature is as follows
#RequestMapping(method = RequestMethod.GET, value = "/payment/{id}/credit/{creditId}/fetch/options", produces = APPLICATION_JSON)
public boolean getCreditOption(#PathVariable String id, #PathVariable String creditId) {
return true
}
This is giving me 404 all the time i execute this code. But when i remove the special charachters it works fine and hits the restful service. I also tried to use encodeURIComponent() and then send the value.. but it is still the same case.
Please let me know if there is any way out for this.
Thanks for any help
The % symbol is used for encoding values in URls, see rfc3986 section 2.1. In particular it's expected that there will be two hex digits after the % - which it seems like you are exactly stumbling on to.
You may have to escape the percent (use %25) or choose a different character to substitute.
You can try it on this page, the address is:
http://stackoverflow.com/questions/27641286/encoding-rest-path-variable-in-angularjs
A 1 percent encoded is %31, so you could just as easily go here:
http://stackoverflow.com/questions/2764%31286/encoding-rest-path-variable-in-angularjs

Passing data to another page using AngularJs

I am trying to pass data from one page to another using AngularJs service but whatever value I set in the variables in the service on one page, it is lost on redirection. Is there any particular way to perform the redirection? Below is the flow of my code
//Created a service to pass data
angular.module('Test').service('TestService', function() {
var new_data;
this.addData = function(page_data) {
new_data = page_data;
}
this.getData = function(){
return new_data;
}
});
//Code in controller A:
TestService.addData(data);
$window.location.href = "/static/html/buyer-cart-confirmation.html"
//Code in controller B:
data = TestService.getData();
No data is received in controller B. Can somebody please help me with this.
Thank you!
You can use session storage to serialize / deserialize data across different instances of angular within the same session (tab), and you can use local storage to do the same thing across sessions, (new tab). Here is the code for both:
Session Storage
class SessionStorageService
setStorage:(key, value) ->
json = if value? then JSON.stringify value else null
sessionStorage.setItem key, json
getStorage:(key)->
JSON.parse sessionStorage.getItem key
pageData1:(value=null) ->
#accessor 'pageData1', value
pageData2:(value=null) ->
#accessor 'pageData2', value
# more data values defined here
accessor:(name, value)->
return #getStorage name unless value?
#setStorage name, value
angular
.module 'app.Services'
.service 'sessionStorageService', SessionStorageService
Local Storage Service
class LocalStorageService
setStorage:(key, value) ->
json = if value? then JSON.stringify value else null
localStorage.setItem key, json
getStorage:(key)->
JSON.parse localStorage.getItem key
clear: ->
#setStorage(key, null) for key of localStorage
pageData1:(value=null) ->
#accessor 'pageData1', value
pageData2:(value=null) ->
#accessor 'pageData2', value
# more data values defined here
accessor:(name, value)->
return #getStorage name unless value?
#setStorage name, value
angular
.module 'app.Services'
.service 'localStorageService', LocalStorageService
With that said, you need to ask yourself why you are redirecting to a different page with any expectation that your state will somehow be preserved?
Angular is typically used for Single Page Applications that use routing frameworks like ui-router to manage state transformations, rather than the old-school, click-and-refresh-the-page model.
In other words, you should not redirect unless you intend on starting a brand new Angular application.
I think your logic is wrong, and since you don't provide a Plunker I can't test it at the moment. I think you should go with smth like:
angular.module('Test').service('TestService', function() {
this.addData = function(page_data) {
this.new_data = page_data;
};
return this;
});
and then you access your data like this:
TestService.new_data
I think it will work like this.

How to mock get(id) requests

I am building an application prototype and try to mock the REST web-services.
Here is my code:
var mock = angular.module('mock', ['ngMockE2E']);
mock.run(function($httpBackend){
users = [{id:1,name:'John'},{id:2,name:'Jack'}];
$httpBackend.whenGET('/users').respond(users);
$httpBackend.whenGET(new RegExp('\\/users\\/[0-9]+')).respond(users[0]);
}
Everything is ok, my resource User.query() returns all users, and User.get({id:1}) and User.get({id:2}) returns the same user (John).
Now to improve my prototype, I would like to return the appropriate user, matching the good id.
I read in the angular documentation I should be able to replace the RegExp URI by a function. The idea is to extract the id from the url to use it in respond method.
I then tried this:
$httpBackend.whenGET(new function(url){
alert(url);
var regexp = new RegExp('\\/users\\/([0-9]+)');
id = url.match(regexp)[1];
return regexp.test(url);
}).respond(users[id]);
The problem is the url parameter is always undefined. Any idea to achieve my goal?
By using new function(url) your app tries to instantiate a new object from your anonymous function and pass that new object as the first argument of the $httpBackend.whenGET() call.
Of course, at the time of calling whenGET() no URL is provided, thus it is always undefined.
You should pass the function itself (and not an object instanciated using the function). E.g.:
$httpBackend.whenGET(function (url) {
...
}).respond(users[id]);
UPDATE:
After some more digging it turned out that the option to pass a function as the first argument to whenGET was added in version 1.3.0-beta.3. The docs you were reading probably referred to the latest beta version, while you were using an earlier version.
(Note that even versions 1.3.0-beta.1 and 2 did not provide this option.)
Without getting into much detail, responsible for verifying a matching URL is MockHttpExpectation's matchUrl method:
function MockHttpExpectation(method, url, data, headers) {
...
this.matchUrl = function(u) {
if (!url) return true;
if (angular.isFunction(url.test)) return url.test(u);
if (angular.isFunction(url)) return url(u); // <<<<< this line does the trick
return url == u;
};
The line if (angular.isFunction(url)) return url(u); is the one that gives the option to directly pass a function and was added in version 1.3.0-beta.3 (as already mentioned).
But, if you still want to pass a function to a previous AngularJS version, you could "trick" angular into believing you passed a RegExp, by providing an object with a test method.
I.e. replace:
.whenGET(function (url) {...})
with:
.whenGET({test: function (url) {...}})
See, also, this short demo.
I found a solution by using a function in the respond part instead of the when part:
$httpBackend.whenGET(new RegExp('\\/users\\/[0-9]+')).respond(
function(method, url){
var regexp = new RegExp('\\/users\\/([0-9]+)');
var mockId = url.match(regexp)[1];
return [200, users[mockId]];
}
});

Resources