【问题标题】:Variable in Angular serviceAngular 服务中的变量
【发布时间】:2016-06-30 20:24:07
【问题描述】:

在我的服务中,我有:

angular.module('Name.Common', [])

.service('myData', function($http) {
  $http.get('server.com/json').success(function(data, status, headers, config) {

        this.companies = data;
        var companies2 = data;

    }).error(function(data, status, headers, config) {

    });


    this.getCompanies = function() {
        return this.companies; //?? return companies2; // ?

    };

});

基本上,我只是想从 http 请求中获取一个 json 文件并在函数 getCompanies 中返回它,这是执行此操作的正确方法吗? 任何帮助将不胜感激。

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    在你的服务中你只需要返回请求:

    angular.module('Name.Common', [])
    
    .service('myData', function($http) {
        var self = this;
    
        self.get = function(){
            return $http.get('server.com/json');
        }
    });
    

    然后在您的控制器中处理数据的“.then”:

    var companies;
    
    myData.get()
        .then(function (response) {
            companies = response; //data only available after this is hit
            console.log(companies); 
        });
    

    【讨论】:

    • 很好用!但在我的控制器之外,console.log(this.companies) 打印未定义,有什么想法吗?
    • 这应该可以,您可以更新问题中的控制器代码吗?
    • 我几乎使用了与 K. Burrell 相同的代码,只是我在 myData.get() 方法之后添加了 console.log(this.companies),它打印出 undefined
    • 嗯,这是因为 Angular 的承诺(这里很可笑地解释为 andyshora.com/promises-angularjs-explained-as-cartoon.html)。您在 myData.get() 之外的 console.log 不会等待数据返回执行。简而言之,您只能在 then / catch 函数中使用 http 调用的结果,或者您可以在获得结果后将响应传递给另一个函数。
    • @Doapper 我已经改变了我的答案,尝试提供一些帮助。如果你想记录它,你应该把它记录在 '.then' 中,因为数据在被获取和设置之前是不可用的。
    【解决方案2】:

    好的,我在这里看到的问题。您进行 http 调用并在回调中设置this,但这不是服务的this。与var 相同,它是本地绑定的。所以外部服务功能对此一无所知。 我会建议是这样的。我还没有测试过,但它应该可以工作

    angular.module('Name.Common', [])
      .service('myData', function($http) {
         var _this = this;
         var companies;
    
         $http.get('server.com/json').success(function(data, status, headers, config) {
        _this.companies = data;
        companies = data;
    
        }).error(function(data, status, headers, config) {
    
        });
    
    
        this.getCompanies = function() {
          return _this.companies; // that part I would test if it works with just this.
          // or return companies2
       };
    });
    

    【讨论】:

    • 谢谢,但是当我做 console.log(_this.companies);我有未定义的。 (并且在 http get 之后,console.log(data) 正在工作)
    • 你在哪里做 console.log(),要清楚。类似的东西行不通this.a; $http.get().then(data => this.a = data); console.log(a)
    • 我在getCompanies函数的开头做了console.log(_this.companies)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-16
    • 1970-01-01
    • 2018-11-16
    • 2018-09-10
    • 1970-01-01
    • 1970-01-01
    • 2020-09-17
    相关资源
    最近更新 更多