在AngularJS中调用ajax后执行服务

时间:2016-05-17 10:40:38

标签: javascript angularjs ajax

我需要在ajax调用后在服务工厂中保存数据。这一切都没有location.href。但是当我输入行代码$ window.location.href时它不起作用。 这是代码:

 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)});
        };

其中,factoryService允许进行ajax调用,而commonVarService允许在服务变量中记忆数据。 如果没有$ window.location.href =""这一切都有效,但是当有$ window.location.href时,应用程序在新页面中重定向而不记住变量。 我错在哪里?有一些好的解决方案吗? 提前谢谢。

commonVarService代码是这样的:

  

angular.module(' common_variable',[])       。服务(' commonVarService',函数(){

        /*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;
        }

});

我还试图只将字符串作为参数:

  

commonVarService.setA(" A&#34);   commonVarService.setB(" B&#34);   commonVarService.setC(" C&#34)

但是当我在href链接的新page.html中时,变量A,B,C未定义......我不知道..

谢谢你的支持!

2 个答案:

答案 0 :(得分:1)

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.

答案 1 :(得分:0)

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");