【问题标题】:execute a service after a call ajax in AngularJS在AngularJS中调用ajax后执行服务
【发布时间】:2016-09-13 09:59:58
【问题描述】:

我需要在 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',[]) .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;
        }

});

我也尝试仅将字符串作为参数:

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

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

提前感谢!

【问题讨论】:

  • 请提供setA、setB、setC函数的源码。
  • 你好,我放了set的代码。它可以工作,但是当我输入 $window.location.href="" 时,它不起作用。我不明白为什么..
  • 你如何定义你的路线?是您使用 menu.html 的路线之一吗?
  • 不,我没有定义溃败......我只是在关注这个:stackoverflow.com/questions/26594140/......它可以工作......但带有href。 ..不保存数据...我不想定义路由,只是与对象数组的链接,以便在两个不同的模块之间共享
  • 我认为,行代码 $window.location.href="./menu/menu.html" 在ajax结果之前被调用......但我不知道如何解决它....

标签: javascript angularjs ajax


【解决方案1】:

所以,我在这里解释问题, 当您使用$window.location.href = 'something' . 它会刷新整页,因此无法存储变量,无法恢复新的角度实例。 我建议使用 angular-route 或 angular-ui-router ,如果您正在构建 SPA(单页应用程序),您可以使用 $location.path('/profile')$location.path('/mypage') 更改路线,这将保留状态您的页面。

【讨论】:

  • 嗨,我需要在另一个页面中定义一个与另一个 Angular js 模块的链接,他们只需要共享对象数组...stackoverflow.com/questions/26594140/…....只是在另一个页面中。 html...
【解决方案2】:

问题在于变量的范围,当您更改当前页面位置时,它会再次加载所有 js 文件,因此它也会声明新变量


“var service={};var _a = null;var _b = null;var _c = null;”



"localstorage"

中定义上述变量

设置值localStorage.setItem("_a ", a);
获取价值localStorage.getItem("_a");

【讨论】:

猜你喜欢
  • 2014-06-26
  • 2013-08-08
  • 2017-12-29
  • 1970-01-01
  • 2014-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多