AngularJS $location.search() doesn't return anything - javascript

I am using AngularJS 1.6.4
The url of my homepage is http://localhost:8080/AsumForum/
I am trying to display a success message if user has registered successfully to my web site. If the user is registered, I will redirect him to the home page, and my url looks like this: http://localhost:8080/AsumForum/?registered=true.
The thing is, $location.search() never finds registered=true. I have tried making $locationProvider compatible with HTML5, but that doesn't work either.
Here is my registration.js:
var app = angular.module('reg',[]);
app.controller('valid', ['$scope','$location','$http',
function($scope,$location,$http){
$scope.send = function(){
var date = new Date();
$scope.user.date=date.toString();
$http({
url: 'http://localhost:8080/AsumForum/webapi/users/register',
dataType: 'json',
method: 'POST',
data: $scope.user,
headers: {
"Content-Type": "application/json"
}
}).then(function success(response){
$scope.res = response.data;
$scope.satus = response.status;
console.log('RES: '+$scope.res+'\nSTATUS: '+$scope.status);
window.location="http://localhost:8080/AsumForum/?registered=true";
}, function error(response){
$scope.res = response.statusText;
console.log('Error: +'+$scope.res);
});
}
}]);
And here is my login.js
var app = angular.module('mainPage',[]);
app.controller('regsuc',['$scope','$location',function($scope,$location){
$scope.message = '';
var show = $location.search();
for(var i in show){
console.log(i);
}
if(show==true){
$scope.message="Successfull registered! You can now log in.";
}
}]);
Logs don't return anything. Using console.log(show) returns [object Object].
Do I really have to use routing to pass parameters, or can it be done like I tried?
Note 1: Redirecting with $location.url('http://localhost:8080/AsumForum/?registered=true); doesn't work for me.
Note 2: Using location.search instead of $location.search returns ?registered=true.

Just try the following
you have missed the parameter name in $location.search()
$location.search().registered

Related

How to update $scope variables through a function

I'm currently working on grabbing some data from an endpoint and then updating a variable called $scope.response. I'm not quite sure how to update this variable and render it on screen.
So what happens in the code below:
I get the query string from an iframe's src attribute, and then post it to my endpoint, where I get a particular response called data. I'd like to update $scope.response with this object, and then render it on the view using {{response}}.
Could someone show me how I could do this?
app.controller('MainCtrl', function($scope) {
$scope.response;
API = {};
API.endpoint = 'https://some/endpoint/';
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
function doAjax(callback) {
var q = getParameterByName('QUERY');
jQuery.ajax({
url: API.endpoint + "script.php",
method: "POST",
data: { q: q },
dataType: "json",
success: function (data) {
callback(data);
$scope.response = data;
}
});
}
});
Angular doesn't magically know when a property on an object changes, it would have to keep re-checking all objects all the time to catch such changes. Angular just makes it look like it notices such changes whenever you use any Angular services or events, since those trigger a digest cycle. At the end of a digest cycle, Angular checks objects it knows about for changes and propagates those changes (e.g. updates views etc.).
When you use jQuery, that's "outside" of what Angular knows about. Primarily you should not use jQuery, but Angular's $http service to make any network requests, since Angular will then properly cycle its digestive system.*
* Pun totally intended
If you have to use some non-Angular system (and again, you really don't have to here, at all), then you need to trigger another digest cycle. The best way to do that is with the $timeout service:
app.controller('MainCtrl', function($scope, $timeout) {
...
success: function (data) {
callback(data);
$timeout(() => $scope.response = data);
}
...
});
Why do you use jQuery in Angular?. If you choose Angular, you should be you $http in angular. Remove function doAjax and replace it to $http. You can read doc in here https://docs.angularjs.org/api/ng/service/$http

AngularJs http request concats my data into a JSON key

Sometimes a behavior is so bizarre that I don't even know how to begin to google it. I'm fairly new at Angular, and I am trying to send POST data to my node server from the client. Here is the controller on the client side:
var app = angular.module("groomer", []);
app.controller("gCtrl", function($scope, $http) {
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
$scope.send = function() {
$http({
method : "POST",
url : "/gUpdate",
data: {
gName:$scope.gName,
gPhone:$scope.gPhone,
gWebsite:$scope.gWebsite,
gEmail:$scope.gEmail,
gCustAcct:$scope.gCustAcct,
gAddress:$scope.gAddress,
gNotes:$scope.gNotes
}
}).then(function success(response) {
alert(console.log('Success!'));
}, function error(response) {
alert(console.log('Booooooo'));
});
};
});
What I naively imagine ought to show up at the server is:
req.body = {
gName:'a',
gPhone:'b',
gWebsite:'c',
gEmail:'d',
gCustAcct:'e',
gAddress:'f',
gNotes:'g'
}
But things get weird. What actually shows up at the server as the request body is:
{"{\"gName\":\"a\",\"gPhone\":\"b\",\"gWebsite\":\"c\",\"gEmail\":\"d\",\"gCustAcct\":\"e\",\"gAddress\":\"f\",\"gNotes\":\"g\"}":""}
In case it takes you a second to see what's happening here, that's all of my JSON keys and data in an object, double-quoted, escaped, concatenated as a string, and passed to the server inside an object as a JSON key corresponding to an empty value.
//so
var lifeMakesSense = {gName:'a',gPhone:'b',gWebsite:'c',gEmail:'d',gCustAcct:'e',gAddress:'f',gNotes:'g'}
//becomes
var waitNo = "{\"gName\":\"a\",\"gPhone\":\"b\",\"gWebsite\":\"c\",\"gEmail\":\"d\",\"gCustAcct\":\"e\",\"gAddress\":\"f\",\"gNotes\":\"g\"}"
//then
var whatEven = {waitNo:""} // nailed it
Thoughts?

Angular Js beginner Ajax Call

I'm new to angular js, Inside my controller.js are controllers for my app, which is 100% working. What I'm having problem is how to make an ajax call using angular js. I'm trying to fetch data from my service and pass it to my index.html using this ajax. When I try to debug the code, it only hits on $http but doesn't go through the code inside it. What am I doing wrong here?
$http({
method: 'POST',
url: 'http://someService.site.net/site.aspx',
data:{action:'someAction', position:'founders'},
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function successCallback(response){
var json =jQuery.parseJSON(response);
var htmldata="";
for(i=0; i<json.length; i++)
{
var htmlInfo = '<li><div class=\'col\'><img width=\'100%\' height=\'auto\' src="'+json[i].Image + '" class=\'profile-img\' /><h3>' +json[i].Name+'</h3><p>'+json[i].Title+'</p></div></li>';
htmldata+= htmlInfo;
}
jQuery("#vflist").html(htmldata);
}, function errorCallback(response){
});
Mark your breakpoints on success and error callbacks.
$http is a service. You passed the required data in it's parameter.
$http({})
^options
After calling this $http will do it's work and send a request to the provided url asynchronously. But You don't need to debug that part.
$http({options})
.then(function(data){
// mark 1 breakpoint here
}, function(data){
// mark another breakpoint here
})
Since you are already using jQuery along with Angularjs I would recommend you to use the $.params() function to encode the parameter data.
Your $http would be like
$http({
method: 'POST',
url: 'http://someService.site.net/site.aspx',
data:$.params({action:'someAction', position:'founders'}),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
Also I suggest you to use the Angular way of doing things rather than using jQuery. You might even like it ;)
First thing is: you can simply use your $http function like this:
var config = {
headers : {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
}};
$http.post('http://someService.site.net/site.aspx',
{action:'someAction', position:'founders'},
config)
.success(function(response) {
var json =jQuery.parseJSON(response);
var htmldata="";
for(i=0; i<json.length; i++) {
var htmlInfo = '<li><div class=\'col\'><img width=\'100%\' height=\'auto\' src="'+json[i].Image + '" class=\'profile-img\' /><h3>' +json[i].Name+'</h3><p>'+json[i].Title+'</p></div></li>';
htmldata+= htmlInfo;
}
jQuery("#vflist").html($sce.trustAsHtml(htmldata));
})
.error(function(data, status, headers, config) {
console.log(status);
});
Secondly, as you can see in the above code I have used $sce.trustAsHtml() -- this is required when you are pushing some html to DOM via $http - or it will just show the codes with tags. You have to inject $sce in the controller definition.
put this line before calling ajax this works for me hope for you to
$http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w';
// YmVlcDpib29w you can put any string
This is also given in- https://docs.angularjs.org/api/ng/service/$http

AngularJS $http get data object displays status code instead of response

I have mulled over this for days and can still not figure out what I'm doing incorrectly so any ideas or even shots in the dark are appreciated. I am trying to display the response from a rest service to the user using the using the AngularJS $http get method, but when I print the data object to the console, I consistently receive the number 200 (I'm fairly certain it is giving me the status code). I hit success every time and, upon sending the request, the Chrome debug tool shows me the response with all the correct data. I just can't seem to get it to appear in a variable for display. Let me know if you think of anything! Thanks!
My javascript:
$scope.resendDestinations = [];
$scope.resendDestGet = function () {
var omtTypeCodeString = '';
for(var i = 0; i < $scope.mySelections.length; i++){
if(omtTypeCodeString == ''){
omtTypeCodeString = $scope.mySelections[i].orderHeader.omtOrderTypeCode;
}
else{
omtTypeCodeString = omtTypeCodeString + ',' + $scope.mySelections[i].orderHeader.omtOrderTypeCode;
}
}
$http({
method: 'GET',
url: restService.pom + //service url,
respondType: 'json',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Access-Control-Allow-Credentials': true
},
params: {
orderTypeCode: omtTypeCodeString,
transactionCode: 3
}
}).success(function (status, data, response, header) {
console.log("Success!");
//TODO see if this is being used... has to be
status = parseInt(status);
$scope.resendDestinations = data.multipleOrders;
if (status == 200 && $scope.resendDestinations.length == 0) {
$scope.bigAlert.title = 'Error',
$scope.bigAlert.header = 'Search Error';
$scope.bigAlert.content = 'Current search parameters do not match any results.';
$scope.showBigAlert();
}
else{
$scope.resendDestinations = data;
console.log("Data DestinationList here: ");
console.log($scope.resendDestinations);
console.log(data.multipleOrders);
console.log(data);
}
$scope.isSearching = false;
}).error(function (response, data, status, header) {
//Do error things
});
return $scope.resendDestinations;
};
And the service response:
[{"destCode":3,"destDescr":"Repository","attributes":null},{"destCode":4,"destDescr":"Pipeline","attributes":null},{"destCode":1,"destDescr":"Processor","attributes":null},{"destCode":2,"destDescr":"DEW","attributes":null},
{"destCode":7,"destDescr":"Management System","attributes":null},
{"destCode":8,"destDescr":"Source","attributes":null}]
You have the arguments in the wrong order. It should be: success(function(data, status, headers, config)
See the docs here (click).
Also, the .then() method is generally preferred. If you switch to that, you would access the data like this:
.then(function(response) {
var data = response.data;
var status = response.status;
//etc
});

Wrap angular $resource requests not returning POST data

I'm working on wrapping my $resource requests in a simple wrapper. The main idea
is to be able to add some logic before the request is made. I've followed the nice article written by Nils.
Here you can see a service definition to access the REST API module.
resources.factory('Device', ['RequestWrapper', '$resource', 'lelylan.config', function(RequestWrapper, $http, config) {
var resource = $resource(config.endpoint + '/devices/:id', { id: '#id' });
return RequestWrapper.wrap(resource, ['get', 'query', 'save', 'delete']);
}]);
And here you can see the request wrapper definition.
resources.factory('RequestWrapper', ['AccessToken', function(AccessToken) {
var requestWrapper = {};
var token;
requestWrapper.wrap = function(resource, actions) {
token = AccessToken.initialize();
var wrappedResource = resource;
for (var i=0; i < actions.length; i++) { request(wrappedResource, actions[i]); };
return wrappedResource;
};
var request = function(resource, action) {
resource['_' + action] = resource[action];
resource[action] = function(param, data, success, error) {
(AccessToken.get().access_token) ? setAuthorizationHeader() : deleteAuthorizationHeader()
return resource['_' + action](param, data, success, error);
};
};
var setAuthorizationHeader = function() {
$http.defaults.headers.common['Authorization'] = 'Bearer ' + token.access_token;
};
var deleteAuthorizationHeader = function() {
delete $http.defaults.headers.common['Authorization']
};
return requestWrapper;
}]);
Everything works just fine for the GET and DELETE methods (the ones that does not returns
a body seems), but I can't get $save working. What happens is that when the JSON of the
created resources returns it is not added. I have only the data I've set on the creation
phase. Let me make an example.
In this case we use the wrapped resource. If I try to get the #updated_at attribute I can't
see it. In the Chrome inspector I can see how the resource is successfully created.
$scope.device = new Device({ name: 'Angular light', type: 'http://localhost:9000/types/50bf5af4d033a95486000002' });
$scope.device.$save(function(){ console.log('Device Wrapped', $scope.device.created_at) });
# => undefined
If I use $resource everything works fine.
// Suppose authorization is already set
var Resource = $resource('http://localhost\\:9000/devices/:id');
$scope.resource = new Resource({ name: 'Angular light', type: 'http://localhost:9000/types/50bf5af4d033a95486000002' });
$scope.resource.$save(function(){ console.log('Device Base', $scope.resource.created_at); });
# => 2013-02-09T12:26:01Z
I started to check the angular-resource.js code but after few hours I couldn't really figure
it out. I can't get why the body is returned, but in the wrapper resource it is not accessible.
Any idea or help would be appreciated. Thanks.
While diving into AngularJS source code I've found the solution.
The problem was that the wrapper was returning a function instead of an object and this was giving some problems. The solution is to change the following row in the Wrapper:
return resource['_' + action](param, data, success, error);
with this one:
return resource['_' + action].call(this, params, data, success, error);
Why? The fast answer is because in the source code of angular-resource they use it. Actually #call run the function sending this to the calling object. It is often used to initialize an object. Learn more here.

Categories

Resources