angular encode url search string - angularjs

how do i encode the keyword that get sent to the server and then decode it?
I can't search for keywords containing chars like .? or / at the moment.
The code displaying is wrong because endpoint returns a object.
self.search = function (keyword) {
var endpoint = $location.path(baseEndpoint + "search/").search(keyword),
deferred = $q.defer();
$http.get(HttpRequestUrlHelper.ensureUniqueRequestUrl(endpoint), {
}).success(function (response) {
deferred.resolve(response);
}).error(function (error) {
deferred.reject(error);
});
return deferred.promise;
}
If i use encodeURIComponent() my url is encoded but my controller isn't hit:
request url => /todo/search/Leka%20med%20barnen.?UniqueKey=1404655031784 angular.js:9159
GET http://localhost:49195/todo/search/Leka%20med%20barnen.?UniqueKey=1404655031784 404 (Not Found)

You can use the escape function: http://www.w3schools.com/jsref/jsref_escape.asp

Ended up making a query string instead:
var endpoint = baseEndpoint + "search?keyword=" + keyword,

Related

How to fix $http GET request

Cannot GET the end point despite passing parameter
Trying to pass an id to the end point for a GET request
controller.js
var vid = $routeParams.vidId //get the video id
console.log(vid) //works
$http({
method:'GET',
url:'/thread/',
params:{vid_id:vid},
}).then(function(success){
console.log('success')
}, function(error){
console.log('error')
})
server.js
app.get('/thread/:vid_id', function(req,res){
console.log(req.params.vid_id)
})
I would expect seeing the vid_id on the server console but instead I am getting a 404 error.
angular.js:13531 GET http://localhost:5000/thread/?vid_id=5cb01f6b03fb0b3e6c2abf7f 404 (Not Found)
You are using the params property on $http, which is meant for appending query string parameters to a URL (eg. ?vid_id=123).
You instead need to dynamically set the URL that you are calling, something like this:
var vid = $routeParams.vidId //get the video id
console.log(vid) //works
$http({
method:'GET',
url:'/thread/' + vid // <==== HERE
})
.then(function(success){
console.log('success')
}, function(error){
console.log('error')
});
If that doesn't work, try to make your server display some text on the endpoint instead of just doing a console.log():
server.js
app.get('/thread/:vid_id', function(req,res){
res.send("test");
console.log(req.params.vid_id)
})
Thank you #nevada_Scout:
I modified you suggestion to work like this:
$http({
method:'GET',
url:'/thread/' +JSON.stringify(vid),
}).then(function(success){
console.log(success)
}, function(err){
console.log(err)
})
Problem solved.

ExpressJS IP and AngularJS $http get

I'm trying to learn ExpressJS and I'm having trouble getting IP address from an Express route to display in the browser via Angular controller.
I'm using 2 Nodejs modules (request-ip and geoip2) to get the IP and then lookup geolocation data for that IP. Then trying to use Angular to display the geolocation data in the browser using an Angular $http get call.
My Express route for the IP:
// get IP address
router.get('/ip', function (req, res, next) {
console.log('requestIP is ' + ip);
// geolocation
geoip2.lookupSimple(ip, function(error, result) {
if (error) {
//return res.status(400).json({error: 'Something happened'});//default
return res.sendStatus(400).json({error: 'Something happened'});
}
else if (result) {
return res.send(result);
}
});
});
And my AngularJS controller code:
function MainController($http) {
var vm = this;
vm.message = 'Hello World';
vm.location = '';
vm.getLocation = function() {
$http({
method: 'GET',
url: 'localhost:8000/ip'
}).then(function (result) {
console.log(result);
return vm.location = result;
});
};
};
The Hello World message displays but not the location...? I can also go to localhost:8000/ip and see the JSON result. The result doesn't appear in Chrome's console either. The result is a json object like this:
{"country":"US","continent":"NA","postal":"98296","city":"Snohomish","location":{"accuracy_radius":20,"latitude":47.8519,"longitude":-122.0921,"metro_code":819,"time_zone":"America/Los_Angeles"},"subdivision":"WA"}
I'm not sure why the Hello Word displays and the location doesn't when it seems that I have everything configured correctly... so obviously I'm doing something wrong that I don't see...?
You have initialised 'vm.location' as a string when in fact it is a JSON object.
vm.location = {};
You need to adjust the url paramater in your request to:
url: '/ip'
As you are sending back JSON from Express.js, you should change your response line to:
return res.json(result);
Do you call vm.getLocation() somewhere in your code after this?
The data you need is under result.data from the response object.
Also in order to display the data in the html you have to specify which property to display from the vm.location object (vm.location.country, vm.location.city etc..).
From angular docs about $http:
The response object has these properties:
data – {string|Object} – The response body transformed with the transform functions.
status – {number} – HTTP status code of the response.
headers – {function([headerName])} – Header getter function.
config – {Object} – The configuration object that was used to generate the request.
statusText – {string} – HTTP status text of the response.
Is this express js and angular hosted on the same port? If so please replace your
$http({
method: 'GET',
url: 'localhost:8000/ip'
}).then(function (result) {
console.log(result);
return vm.location = result;
});
with
$http({
method: 'GET',
url: '/ip'
}).then(function (result) {
console.log(result);
return vm.location = result;
});
It may be considered as CORS call and you have it probably disabled.
You can also specify second function to then (look code below) and see if error callback is called.
$http({
method: 'GET',
url: '/ip'
}).then(function (result) {
console.log(result);
return vm.location = result;
}, function (error) {
console.log(error);
});

Promise Chains in angularjs

I am uploading attachments using rest api in SharePoint 2013,for this I need to call upload attachment method on synchronous.
Because If I call upload attachment method asynchronous I am getting 409 conflict error.
How to chain promise objects in for loop.i.e I want to call second attachment method in first attachment success and so on..
Please help me in best approach of chaining of promises in for loop.
Common method for saving attachments:
var saveFileAngularJS = function (file, url) {
var deferred = $q.defer();
getFileBuffer(file).then(function (fileArrBuffer) {
$http({
method: 'POST',
url: baseUrl + url,
headers: {
'Accept': 'application/json;odata=verbose',
'Content-Type': undefined,
'X-RequestDigest': jQuery("#__REQUESTDIGEST").val()
},
data: new Uint8Array(fileArrBuffer),
transformRequest: []
}).then(function successCallback(data) {
deferred.resolve(data);
alert('Successfully saved.', data);
}, function errorCallback(error) {
deferred.reject(error);
alert('Failed to save!!!.', error);
});
});
return deferred.promise;
};
Method calling :
for (var i = 0; i < $scope.files.length; i++) {
var file = $scope.files[i]._file;
var response = lssDealService.insertAttachment(transactionId, file);
}
var insertAttachment = function (dealId, file) {
var attachmentUrl = listEndPoint + "/GetByTitle('TransactionList')/GetItemById(" + dealId + ")/AttachmentFiles/add(FileName='" + file.name + "')";
return baseService.saveFile(file, attachmentUrl);
};
Insert attachment will call SaveFile method.
I want to run this for loop sequentially, once the loop has been completed I need to process all promises and display success message to user.
Please help me to writing the chaining promises in effective way.
Lets say you have the attachements as an array,
function uploadMyAttachements() {
return myAttachements.reduce(function(promise, attachment) {
return promise.then(function () {
return upload(attachment);
})
.then(function(result) {
console.log('RESULT FOR LAST UPLOAD', result);
});
}, Promise.resolve());
}
function upload(attachment) {
//upload the attachment to sharepoint
//and return a promise here
}
uploadMyAttachements().catch(function(err) {
//if anything in the promise chain fails
//it stops then and there and CATCHED here
});
Now whats happening here, using the Array.reduce, we create a chain of promises like shown below
upload(0).then(handleResult_0).upload(1).then(handleResult_1)....
and it execute one by one as you expected
Throwing my 2 pennies:
$scope.attachments = []; //modified via binding.
function uploadAttachments(){
//Reduce the files array into a promise array with the uploadOne method
//then return the promise when every promise has been resolved or one has rejected.
return $q.all($scope.attachments.reduce(uploadOne, []));
}
function uploadOne(file){
//Upload one, return promise. Use $http or $resource.
}
//Note - a more advanced way of doing this would be to send the files as batch (one
//$http post) as FormData. There are some good wrappers for angular.
$scope.upload = function(){
uploadAttachments().then(function(results){
//Array of results
}).catch(function(e){
//Error handler
});
}

Variable Access in JSON Body

I have a search method for domains that returns whether or not it can be registered. I am having trouble accessing the 'status' string in the returned JSON body.
Here is my AngularJS code for accessing the API:
hosting.searchDomain = function() {
var domain = hosting.domain;
var tld = hosting.tld;
var url = apUrl + 'api/domains/available.json?auth-userid='+ resellerId +'&api-key='+ key +'&domain-name='+ domain +'&tlds='+ tld +'';
$http({
method: 'GET',
url: url,
}).then(function successCallback(response) {
var data = response.data;
console.log(data);
hosting.searchResults = data;
}, function errorCallback(response) {
console.log('Eror: ', response);
});
}
And this returns something like this when you search mydomains.com:
{"mydomains.com":{"status":"regthroughothers","classkey":"domcno"}}
I don't understand how I would access the status string?
Try:
console.log(data["mydomains.com"].status);
See it working here:
https://jsfiddle.net/n6jqbcp9/
First, convert the JSON to a JavaScript object.
data = JSON.parse(data);
Access the property status:
status = data["mydomains.com"]["status"]

How to know from controller if http.post().then... was successful?

I have a controller which uses the following line to post data to server through a factory called SendDataFactory:
SendDataFactory.sendToWebService(dataToSend)
And my factory SendDataFactory looks like this:
angular
.module('az-app')
.factory('SendDataFactory', function ($http, $q) {
var SendData = {};
/**
* Sends data to server and
*/
SendData.sendToWebService = function (dataToSend) {
var url = "example.com/url-to-post";
var deferred = $q.defer();
$http.post(url, dataToSend)
//SUCCESS: this callback will be called asynchronously when the response is available
.then(function (response) {
console.log("Successful: response from submitting data to server was: " + response);
deferred.resolve({
data: data
});
},
//ERROR: called asynchronously if an error occurs or server returns response with an error status.
function (response) {
console.log("Error: response from submitting data to server was: " + response);
deferred.resolve({
data: data
});
}
);
return deferred.promise;
}
return SendData;
});
I have seen some examples in here and the internet with
$http.post().success...
but I want to use
$http.post().then...
since angular documentation says:
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.
What I need:
Now in my controller I need to check if the $http.post().then... was successful or not and then do something based on success or fail. How can I achieve this?
I think this is what you meant:
$http.post(url, dataToSend)
//SUCCESS: this callback will be called asynchronously when the response is available
.then(function (response) {
console.log("Successful: response from submitting data to server was: " + response);
deferred.resolve({
data: response //RETURNING RESPONSE SINCE `DATA` IS NOT DEFINED
});
},
//ERROR: called asynchronously if an error occurs or server returns response with an error status.
function (response) {
console.log("Error: response from submitting data to server was: " + response);
//USING THE PROMISE REJECT FUNC TO CATCH ERRORS
deferred.reject({
data: response //RETURNING RESPONSE SINCE `DATA` IS NOT DEFINED
});
}
);
return deferred.promise;
}
In your controller you now can use:
SendDataFactory.sendToWebService(dataToSend)
.then(function(data) { /* do what you want */ })
.catch(function(err) { /* do what you want with the `err` */ });
Reject the promise instead of resolving it when it is rejected by $http.
/**
* Sends data to server and
*/
SendData.sendToWebService = function (dataToSend) {
var url = "example.com/url-to-post";
var deferred = $q.defer();
$http.post(url, dataToSend)
//SUCCESS: this callback will be called asynchronously when the response is available
.then(function (response) {
console.log("Successful: response from submitting data to server was: " + response);
deferred.resolve(response.data); // Resolving using response.data, as data was not defined.
},
//ERROR: called asynchronously if an error occurs or server returns response with an error status.
function (response) {
console.log("Error: response from submitting data to server was: " + response);
deferred.reject(response.data); // Rejecting using response.data, as data was not defined.
}
);
return deferred.promise;
}
You can then call it from your controller the same way as you handle the callback in the service using then.
Since $http returns a promise, it can be simplified further though using promise chaining. This way there is no need to use an extra deferred object.
/**
* Sends data to server and
*/
SendData.sendToWebService = function (dataToSend) {
var url = "example.com/url-to-post";
return $http.post(url, dataToSend)
//SUCCESS: this callback will be called asynchronously when the response is available
.then(function (response) {
console.log("Successful: response from submitting data to server was: " + response);
return response.data; // Resolving using response.data, as data was not defined.
},
//ERROR: called asynchronously if an error occurs or server returns response with an error status.
function (response) {
console.log("Error: response from submitting data to server was: " + response);
return $q.reject(response.data); // Rejecting using response.data, as data was not defined.
}
);
}

Resources