Reputation: 37
I need to save data in a service factory after a ajax call. It all works without location.href. But it doesn't work when I put the line code $window.location.href. This is the code:
scope.res = function(id){
factoryService.getLista(id,"en-US","")
.then (function(response){commonVarService.setA(response.A);
commonVarService.setB(response.B);
commonVarService.setC(response.C);
$window.location.href="./menu/menu.html";
})
.catch(function(err) {console.log(err)});
};
Where, factoryService allow to make an ajax call, wherease commonVarService allow to memorize data in variables of service. If there isn't the $window.location.href="" it all works, but when there is the $window.location.href, the application redirect in the new page without memorize the variable. where is it my Error? Is there some good solution? Thanks in advance.
the commonVarService code is this:
angular.module('common_variable',[]) .service('commonVarService',function(){
/*a*/ this.getA = function(){ return this._a; } this.setA = function(a){ return this._a=a; } /*b*/ this.getB = function(){ return this._b; } this.setB = function(b){ return this._b = b; } /*c*/ this.getC = function(){ return this._c; } this.setC = function(c){ return this._c = c; } });
I also tried to put simply only the string as parameter:
commonVarService.setA("A"); commonVarService.setB("B"); commonVarService.setC("C")
but when I'm in the new page.html of href link, the variable A , B, C are undefined...I don't know..
Thanks in adavance!
Upvotes: 1
Views: 134
Reputation: 278
So, I am explaining the problem here,
When you are using$window.location.href = 'something'
.
It does a full page refresh, so it cannot store the variable,reinstatiate a new angular instance.
i would suggest to use , angular-route or angular-ui-router , where you can change the route by using this , $location.path('/profile')
or $location.path('/mypage')
if you are building a SPA(Single page application) ,which will retain the state of your page.
Upvotes: 1
Reputation: 801
Issue is with scope of variables when you are changing current page location it will load all js files again so it will also declare new variables
"var service={}; var _a = null; var _b = null; var _c = null;"
Define above variables in "localstorage"
i.e. to Set Value : localStorage.setItem("_a ", a);
to Get Value : localStorage.getItem("_a");
Upvotes: 0