Losing Cookies when navigating to a new page in AngularJS - angularjs

I am trying to develop 2 pages:
Page 1: Normal Login Page login.html
Page 2: Home Page home.html
I am using AngularJS to code the scripts in these pages.
I have to transfer some data between these two pages. So i decided to use cookies (I tried to use Services but i didn't know how to write the same service for 2 separate files).
In the Login page i saved the cookies as follow :
var resultObj = {'loginid',result};
$cookies.dotobject = resultObj;
window.location = 'Home.html';
I checked that this cookie is saved correctly (Console.log(resultObj))
However when i open the home page i try to read this cookie using:
var result = $cookies.dotobject;
console.log(result) //To check if it worked
But it didn't, i got undefined.
My question is can I use $cookies in this case ? And why does it disappear ?
If cookies are not useful in this case how to use a service between 2 different pages containing 2 different controllers ?
Excuse me if this questions aren't from a good quality since i am still learning these concepts.
EDIT
I tried to write in the same document :
console.log(result);
$cookies.put('loginid',result);
var loginida = $cookies.get('loginid');
console.log(loginida);
But the $cookies.get does not work ; It gives also undefined . Any ideas ?

Related

AngularJs Cookie : Share across multiple tabs

I am developing an angjs application.
Used angjs 1.6.
Following is my code to create a cookie
$cookies.put('globals', $rootScope.globals);
When i open a new tab, I dont find this cookie variable "globals".
How to share cookies across multiple tabs?
cookies are document specific. So, you are not getting in other tab. Please go for ngStorage or use localStorage
and one more thing is even you want to store non-prmitive data(object, array etc) in cookies/storage, you must stringfy before pushing and should be parsed after getting.
eg: $cookies.put('globals', JSON.stringify({name: 'My_name'}));
var myName = JSON.parse($cookies.get('globals'));
Check if this helps you out:
$cookies.put('globals', $rootScope.globals, {domain: 'yourdomainhere'});

AngularJS not setting location state with "skipReload"

I am working on a site that is transitioning to Angular - it uses Angular for single page application navigation and a new feature I'm currently working on is written entirely in Angular.
The rest of the site takes navigation results and returns them through the SPA model, the feature I'm working on runs entirely in a single page, but in order to make links shareable and bookmarkable it changes the URL in relation to the current state of the page.
So when someone selects a new subsection of the new feature, we have some code like this in the subsection service:
function setLocationForSubsection(subsection) {
var path = subsection.id ? "subsections/" + subsection.id + "/" + subsection.urlSlug : "";
$location.path("/section/" + path).search({}).skipReload();
};
If they follow a link to elsewhere in the site ( which goes through a $stateProvider.state('all', { url: '*urlPath?id', controller... pattern ) it works correctly.
If they then hit the back button, they come back to the correct page and setLocationForSubsection is called. If they click on the same link outside of the subsection again, nothing happens.
So this course of action occurs:
/section/2/subsection-name <- works.
/news <- works
back button ( /section/2/subsection-name ) <- works
/news fails
As far as I can tell, the problem arises because the location path setting fails to push the location into the angular state in this situation, so as far as angular is concerned it is still on /news and so when I try to navigate back there, it doesn't pick it up as a navigation event. I have tried using $window.history.pushState(null, 'any', $location.absUrl()); manually, but it doesn't seem to make any difference. If I drop the skipReload call it works but reloads the contents of the page, which is superfluous in this case. I'm using that approach for now, but I would like to know if there is a better option.
Is there a way to tell angular that a state change has happened in this case?

Angularjs route html5Mode direct url in .net MVC

I've seen a couple of similar questions/answers, but I still seem to be missing something. Everything works fine until I refresh the page or go to a URL directly.
I can either get a 404 or create the same url in mvc, but then it serves up the partial only on refresh and doesn't include the layout page.
There were a couple that suggested changing the MVC routing to:
routes.MapRoute(
name: "Application",
url: "{*url}",
defaults: new { controller = "Home", action = "Index" }
);
When that is implemented, it means I can't access any other URL on the site normally and unless I am missing something, basically everything has to be put into a rest api or write a custom route for every url. Neither sounds very good.
So how can I have an html5 url (no hash tags in valid browsers) with angularjs and be able to browse to eg. Home/About or Home then click a link to About and have them show up the same with the same base layout page?
This may not be the best answer, so if anyone has any better ideas, please comment, otherwise maybe this will help someone else.
I realized that the MVC Ajax directive didn't detect angular calls, so I couldn't automate that side.
So in angular I did something like
.when('/Home/Contact', {
templateUrl: '/Home/NgContact'
In my MVC controller I have 2 actionresults:
public ActionResult NgContact(){
ViewBag.IsFromNg = 1;
return Contact();
}
public ActionResult Contact() {
return View("Contact"); //have to type in name, may look for NgContact.cshtml
}
Finally on any views these may call I put:
#if (ViewBag.IsFromNg == 1){ Layout = null; }
So there is a little repetition with each Actionresult having 2 copies, 1 for a full page load and 1 for any calls angular makes, but only 3 extra lines each.

Redirect AngularJS up one directory

Im using Angular.js and I have several routes:
http://localhost/tool/new
http://localhost/tool/report/#/59FD59D56F20DDFA722F5B31796CAE3396C
tool/new is the form where a user would create a new report using the tool. The program then runs in the background and the user can access the report by going to tool/report/#/their-id where their-id is a big SHA1 hash.
That hash is a route param, if that hash is invalid I need to redirect the user back to tool/new. The problem Im having is that the program file structure is:
tool/new/index.html // The create new report form
tool/report/index.html // The report area
I've been trying to use $location to redirect like this:
$location.path('/new');
But it just redirects to tool/report/#/new and that doesn't help.
Does anyone know how to tell Angular to move up one directory and redirect?
Based on the answer from Branimir, I get the URL and trim it at the current (report) directory. I do this because the tool name and domain can change depending on the server its located on. This worked for me.
var dialog = $dialogs.notify('We were unable to find your tool run.','<p>It is possible that the URL you have entered is incorrect or that your tool run has been deleted due to inactivity.</p><p>Please confirm your URL and try again; or create a new tool run.</p>');
dialog.result.then(function(btn){
var url = $location.absUrl();
var base = url.substring(0,url.indexOf('/report/'));
window.location = base + '/#/new';
},function(btn){});
Note Im using $dialogs from here https://github.com/m-e-conroy/angular-dialog-service/blob/master/dialogs.min.js to tell the user the id is bad.
If you want to reload page use:
$window.location.href = 'http://localhost/tool/new';
$location service doesn't reload a page, it changes a URL in the same AngularJS application.

AngularJS - How can I do a redirect with a full page load?

I want to do a redirect that does a full page reload so that the cookies from my web server are refreshed when the page loads. window.location = "/#/Next" and window.location.href = "/#/Next" don't work, they do an Angular route which does not hit the server.
What is the correct way to make a full server request within an Angular controller?
For <a> tags:
You need to stick target="_self" on your <a> tag
There are three cases where AngularJS will perform a full page reload:
Links that contain target element
Example: link
Absolute links that go to a different domain
Example: link
Links starting with '/' that lead to a different base path when base is defined
Example: link
Using javascript:
The $location service allows you to change only the URL; it does not allow you to reload the page. When you need to change the URL and reload the page or navigate to a different page, please use a lower level API: $window.location.href.
See:
https://docs.angularjs.org/guide/$location
https://docs.angularjs.org/api/ng/service/$location
We had the same issue, working from JS code (i.e. not from HTML anchor). This is how we solved that:
If needed, virtually alter current URL through $location service. This might be useful if your destination is just a variation on the current URL, so that you can take advantage of $location helper methods. E.g. we ran $location.search(..., ...) to just change value of a querystring paramater.
Build up the new destination URL, using current $location.url() if needed. In order to work, this new one had to include everything after schema, domain and port. So e.g. if you want to move to:
http://yourdomain.example/YourAppFolder/YourAngularApp/#/YourArea/YourAction?culture=en
then you should set URL as in:
var destinationUrl = '/YourAppFolder/YourAngularApp/#/YourArea/YourAction?culture=en';
(with the leading '/' as well).
Assign new destination URL at low-level: $window.location.href = destinationUrl;
Force reload, still at low-level: $window.location.reload();
After searching and giving hit and trial session I am able to solove it by first specifying url like
$window.location.href = '/#/home/stats';
then reload
$window.location.reload();
I had the same issue. When I use window.location, $window.location or even <a href="..." target="_self"> the route does not refresh the page. So the cached services are used which is not what I want in my app. I resolved it by adding window.location.reload() after window.location to force the page to reload after routing. This method seems to load the page twice though. Might be a dirty trick, but it does the work. This is how I have it now:
$scope.openPage = function (pageName) {
window.location = '#/html/pages/' + pageName;
window.location.reload();
};
Try this
$window.location.href="#page-name";
$window.location.reload();

Resources