简体   繁体   English

如何在角度工厂中实现API

[英]How to implement API into angular factory

Well, I know that javascript is asynchronize. 好吧,我知道javascript是异步的。 So if I write my code as below, and then I call it in controller I will got '[]' as a result. 因此,如果我按如下方式编写代码,然后在控制器中调用它,结果将为“ []”。

But I the http get request to finish it process before doing anything else. 但是我在执行任何其他操作之前先获得了http get请求以完成此过程。 Or my ionic apps will breakdown. 否则我的离子应用程序将崩溃。 So How could I do this? 那么我该怎么做呢?

var starter = angular.module('starter', ['ionic']); 

starter.factory('AllEvent', function($http) {
  var allEvent = [];
  $http.get('/api/event/new').success(function(data) {
    var allEvent = {
      all: function() {
        return data;
      },
      remove: function(Event) {
        $data.splice(data.indexOf(Event), 1);
      },
      get: function(_id) {
      for (var i = 0; i < data.length; i++) {
        if (data[i]._id === _id) {
          return data[i];
        }
      }
      return null;
      }
    };
  });
  return allEvent;
});

PS this code is a modified code from tabs template in ionic. PS此代码是ionic中选项卡模板的修改代码。

Why would you use the same variable as an Array and an object ? 为什么要使用与数组和对象相同的变量?

var starter = angular.module('starter', ['ionic']);

starter.factory('AllEvent', function($http) {
    return {
        getNew : function(){
            return $http.get('/api/event/new').success(function(data) {
                return {
                    all: function() {
                        return data;
                    },
                    remove: function(Event) {
                        $data.splice(data.indexOf(Event), 1);
                    },
                    get: function(_id) {
                        for (var i = 0; i < data.length; i++) {
                            if (data[i]._id === _id) {
                                return data[i];
                            }
                        }
                        return null;
                    }
                };
            });
        }
    }
});

In the Controller 在控制器中

AllEvent.getNew().then(function(eventObj){
   eventObj.all();
})

Hope this works .. 希望这可以..

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM