angular.js - 怎么在angular初始化时$http为factory赋初值
phpcn_u1582
phpcn_u1582 2017-05-15 16:54:00
0
4
687

因为觉得factory是单例的所以把http结果作为factory的返回值,怎么做到在angular初始化时$http为factory赋初值?
angular.module('some',[]) .factory('factory',function($http){ var some = {}; $http.get('url') .success(function(resp){ some.data = resp; }) return some.data; })
现在类似是这样写的,我就希望angular初始化的时候把从服务器取一些值之后可以一直用

phpcn_u1582
phpcn_u1582

reply all (4)
習慣沉默

You must have discovered that the problem with your writing is that data acquisition is asynchronous.some.data刚开始还是undefined。但你的直觉是对的:通用的数据应当放在factoryserviceInside. Now to solve the asynchronous problem, there are three solutions:

  1. Convert to sync. This is the most direct solution. Render the required data directly in the template on the server side, using thefactory从HTML中取数据,一般用inputtag. Along this line of thinking, a better way is to set up the resources before starting the Angular App. You can refer to this article: http://harttle.github.io/2015/05/31/angular-scope-initialize.html#1

  2. Asynchronous callback. Usefactoryto return a callback function, written like this:

    javascriptxxx.factory('some', function($http){ var some = {} function get(cb){ if(some.data) return cb(some.data); $http.get('').success(function(d){ cb(some.data = d); }); } return get; }); ... some.get(function(data){ console.log(data); });
  3. Use Promise/Deffered mode for asynchronous operation. As projects become more and more complex,Promise is the ultimate solution. Angular provides an implementation of this pattern, which will return a Promise instance. Used like this:$q,它是一个Service,$http.get

    javascriptxxx.factory('some', function($q, $http){ return $http.get(''); }); ... some.success(function(data){ console.log(data); });
    给我你的怀抱

    angular.run(fn)

      某草草

      angularjs $http does not support synchronous acquisition

      Want to initialize or output response.write from backend to frontend
      Or use jquery's ajax blocking to get the data and then initialize angular
      For routing, you can use resolve to inject controller

      http://stackoverflow.com/questions/16286605/initialize-angularjs-servi...

        PHPzhong

        There are thousands of initialization methods. The key is not whether the value you want is obtained synchronously or asynchronously, but where and when do you use it? Goal orientation determines what method you use for initialization. Of course using promises is recommended in most cases.

          Latest Downloads
          More>
          Web Effects
          Website Source Code
          Website Materials
          Front End Template
          About us Disclaimer Sitemap
          php.cn:Public welfare online PHP training,Help PHP learners grow quickly!