AngularJS $location.path(url) not Redirecting - javascript

All,
I have an AngularJS PhoneGap app I am working on. I am stuck on one redirect that occurs immediately after receiving an API call response. My code is located at gist.github.com
My issue is on line 300 of controllers.js, where I am calling my redirect within a then() block.
UserService.login($scope.user.email, $scope.user.password)
.then(function(response) {
globals.session_id = response.data.meta.session_id;
globals.logged_in_userId = response.data.response.users[0].id;
if ($scope.user.remember === true) {
window.localStorage.setItem("_session_id", response.data.meta.session_id);
window.localStorage.setItem("logged_in_userId", response.data.response.users[0].id);
} else {
window.localStorage.removeItem("_session_id");
window.localStorage.removeItem("logged_in_userId");
}
})
.then(function() {
$location.path("/tab/locations");// <=== This line doesn't cause an error but does not result in a redirect
})
.
catch (function(response) {
alert(JSON.stringify(response));
});
If anyone could please help me out, I'd appreciate it!
Thanks,
Bruce

Try $rootScope.$apply(); after $location.path()
OR
$scope.$apply(function() {
$location.path("/tab/locations");
});
You can also use $location.url()

Your then handler needs to return something so that the promise will be stilled resolve for the next condition.
Just add return response at the end of your then handlers.

It appears the issue was actually in my app.js run function call. On location change it looks at a global variable to see if a username has been set yet, and if not, it intercepts the call to send the client to the login page. Once I moved my code inside the OnLocationChange handler to look at the variable there, it redirected properly.
Thanks,
B

Related

How to put a function inside event.respondWith() in javascript that returns a response

I have a service worker that should return a cached file if it's of a certain type. If not, it should fetch the resource. I put the code that checks if the file is a certain type inside the fetch function. If it is, it returns the cached version. If not, it returns the fetched version. I have found out though, that it sends a network request for the fetch, then returns the cached version (duh).
I don't want this because it undos the purpose of serving the cached version of a large file instead of fetching it if possible. I realized I have to put the if then statement outside of the fetch, but that would mean that I am putting it in as a parameter. This is a problem, because it throws an error. So, I decided to put it inside a function. This returns an invalid response, so I don't know what I am doing wrong. It must be that the function inside the event.respondWith() must not be returning, but why?
My code is:
this.addEventListener("fetch", function (event) {
event.respondWith(function(){
//if the event request is a music file (I have it stored in a folder named music, so if the request is like "music/musicfile.mp3"), then returned the cached version. If not, fetch the file over the network.
if(event.request.url.match(/music\//)){
return caches.match(event.request).then(function(r){
if(r){
return r;
}
else{
return fetch(event.request).then(function(fetchR){
return fetchR;
});
}
});
}
else{
return fetch(event.request).then(function(res){
return res;
}).catch(function(){
return caches.match(event.request).then(function(cacheRes){
if(cacheRes){
return cacheRes;
}
else{
return new Response("Error",{status : 520, statusText : "Error fetching cache", headers :new Headers({"Content-Type":"text/html"})});
}
});
});
}
}
);
});
I know this is probably not the best approach, but if there is another way I would gladly like to improve it for best practices.
I found out how to do this. Since event.respondWith() takes a response, not a function, if you give it a function it treats that as a response, it doesn't run it. What you have to do is call an IIFE (immediately invoked function expression), that way your function gets executed and returns a response). IIFE syntax:
(function{
console.log("I was run immediately after I was created!");
})();

How to test JQuery fail callback?

This is jquery function:
$.get("/url", function(){
//success
}).fail(function(){
//fail <---- how to make code go in there.
});
Problem is how to let program goes into .fail block, I use .Net MVC, However, set break point in Controller doesn't trigger a timeout exception then leads to fail callback.
Don't know how people test this.
Should I start looking at some tools ?
Put this in your Controller method:
return new HttpStatusCodeResult(HttpStatusCode.NotFound);
Use an invalid endpoint URL. You should get 404 - not found http status code error.

How to make casperJS wait until .change() event is finished?

I am triggering a change event in my casperJS script which triggers an AJAX request like such:
casper.evaluate(function(i) {
$("form:eq(2) select option:eq(" + i + ")").attr("selected", "selected").change();
},i);
How can I make casperJS wait until the underlying AJAX request has been finished? Already tried to look at the docs but I am more or less stuck. Can anyone guide me into the right direction?
You can always do this in a static way using casper.wait.
casper.thenEvaluate(function(i) {
// change()
},i).wait(5000).then(function(){
// further processing
});
And hope that the request is done in 5 seconds, but maybe you lose some time waiting when the request is done much sooner than 5 seconds. The problem is that as soon as the request is finished doesn't mean that the page is ready/changed.
Another possibility would be to wait for the request to finish, but for this to work you will need to register for the success event of the request somehow. Most of the time you don't have access to this from the global scope. If you do then you can use
casper.thenEvaluate(function(i) {
window._someUniqueVariable = false;
registerSuccessEvent(function(data){
window._someUniqueVariable = true;
});
},i).waitFor(function check(){
return this.evaluate(function(){
window._someUniqueVariable = true;
});
}, function(){
// further processing
});
A more Casper-way of doing that would be to use casper.waitForResource, but then you would need to know the url beforehand or at least able to deduce it from the page.
In the general case, when the request comes back it does something to your page. So you should be able to waitForSelector with a new element or waitForSelectorTextChange or waitUntilVisible etc.
you probably missed waitForResource
from the docs: http://casperjs.readthedocs.org/en/latest/modules/casper.html#waitforresource
casper.waitForResource("you url here", function()
{
// place your code here
});

Angularjs - $location.path / $location.url changes URL but doesn't refresh page

Working with Angular and im running into a few issues using $location.url & $location.path
The URL changes at the top of the page to /users/sign_in but I don't see the view until I manually refresh the page, then it appears?
function error(response) {
if (response.status == 401) {
$rootScope.$broadcast('event:unauthorized');
$location.url('/users/sign_in');
};
};
I am not getting any errors.
You're doing a bit too much in your function. You're attempting to change the URL but also return a response. You can try using a $scope.$apply() right after the $location.url call, however you should consider splitting this logic so that the redirect occurs based on the returned response, or don't return any response from the error function.

How to change window.location.href in JavaScript and then execute more JS?

I have code snippent which is executed on click of a link which is as below
cj_redirecturl="/HomeWork/main/load_course";
utility.xhttprw.data(cj_redirecturl,{data:courseid},function(response){
if(response){
window.location.href=base_url+"main";
///next
utility.xhttprw.data(redirecturl,{data:""},function(response){
if(response){
id=ent;
document.getElementById('content').innerHTML=response;
// Assignemnt module
//Call function from javascript/assignment.js file to display particular assignment (ent:means assignment_id) //
if(con==5)
{
get_assignment_id(ent);
}
if(con==9)
{
get_content_details(ent);
}
} //end of response
},false,false,false,'POST','html',true);
}
},false,false,false,'POST','html');
in above code window.location.href=base_url+"main";redirects the page to its respective page but this stops the execution of the code written just next to it. Now I want this code to be executed as it is been written i.e. firstly the code should take me to the respective "main" page and then code writte after that must execute and give me a required output.
Can someone guide me to achieve this?
window.location.href = base_url + "main"; <- when you load this page, call your code defined at ///next
you will have to add some parameters:
window.location.href=base_url+"main?parameter=true";
The other way would be to load the page with ajax into a div in the html.
Have a look at $.ajax() from jQuery.
please try to write
window.location.href = base_url + "main";
just before the end of if condition or use
setTimeout('window.location.href=base_url+"main"', 2000);
As already been noticed, you cant execute code after you went to another page
What you can do is to create redirector function, that will pass your function in cookie and ,redirect and then eval it on next page. (with another call to that redirector on next page)
But you should be aware of number of issues
1) Packing. It is upon you to decide how you pack cookie.
2) Encription. If you pass non-packed OR non-encrypted cookie the "bad user" can pass some malware code inside that cookie.
3) You should have VERY, VERY good reasons to do it.
This way is too complicated, hard to code, hard to maintain
Much better if you do additional server-side controls, save it somewhere and reload on next page with one more request.
You'll need to wrap the rest of the JS code inside a window.onbeforeunload callback.
See here: Intercept page exit event
You need to use the onBlur event to continue to execute js code before exit from the page.
Example:
function downloadExcel()
{
// Your code...
$('#download_excel_button').hide();
$('#download_spinner').show();
window.location.href = download_page;
window.onblur = function(event)
{
// other event code...
$('#download_spinner').hide();
$('#download_excel_button').show();
}
}

Categories

Resources