为了初始化服务等待服务器数据 [英] Wait for server data in order to initialize service

查看:169
本文介绍了为了初始化服务等待服务器数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建时,应用程序加载首次从服务器获取数据的角度服务的一次,然后我就可以从本地服务对象查询数据。以下是我试图做到这一点:

I want to create an angular service that when the app is loaded for the first time will fetch data from the server once and then I'll be able to query the data from the local service object. Here's how I tried to do it:

angular.module('my.services').factory('Properties', function ($http) {

  var properties = $http.get("/properties");

  return {
    get: function (property) {
      // Logic here
      console.log(property);
    }
  }
});

问题是 - $ http.get()是异步的,为了达到我想要做的,我一定要同步使用它。有没有办法与本土AngularJS办呢?或者我必须使用XHR要求呢?

Problem is - $http.get() is asynchronous and in order to achieve what I'm trying to do, I have to use it synchronously. Is there a way to do it with "native" AngularJS? Or I must use an XHR call for this?

推荐答案

您可以尝试做这样的事情。

You can try to do something like this

angular.module('my.services').factory('Properties', function ($http) {

  var propertiesPromise = $http.get("/properties");

  return {
    get: function (property) {
      propertiesPromise.then(function(properties){
        console.log(properties);
      });
    }
  }
});

这篇关于为了初始化服务等待服务器数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆