使用Service AngularJs 1.6.1在控制器之间共享数据 [英] Share data between controllers using Service AngularJs 1.6.1

查看:131
本文介绍了使用Service AngularJs 1.6.1在控制器之间共享数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作有关侏儒的普查应用程序。此应用程序显示所有侏儒的列表,并允许您对其进行过滤。

I am making a census app about gnomes. This app shows a list of all gnomes and allows you to filter it.

问题是过滤器不起作用!我的 gnome-filter 控制器无法与 gnome-list 控制器通信。为了解决此问题,我尝试通过在StackOverlflow中阅读以下答案来创建服务:

The problem is that the filter is not working! My gnome-filter controller cannot communicate with the gnome-list controller. To solve this problem I tried creating a service by reading this answer in StackOverlflow:

  • https://stackoverflow.com/a/21920241/1337392

不过,在创建了我认为可以很好地解答的副本之后,它仍然无法正常工作。

However, after creating what I believe to be a fine replica of the answer, it is still not working.

应用程序首次加载时, gnome-list 向gnome普查服务器发出请求,以获取所有gnome并显示它们。

When the app first loads, gnome-list makes a request to the gnome census server to get all the gnomes and show them.

但是,有很多侏儒,所以我为您提供了一个过滤器,可以通过使用来过滤它们,并且只获取那些头发已染过的侏儒。 gnome-filter

However, there are a lot of gnomes, so I offer you the option to filter them and only get those with read hair, by using the gnome-filter.

不幸的是,即使我向服务器发出请求,但得到答复,我的服务仍无法正常工作。 ..

Unfortunately, even though I make a request to the server, and I get an answer, my service is not working...

/*global angular*/

(function() {
  var app = angular.module("census", []);

  app.controller("gnomeFilter", function(DataShareServ) {
    var self = this;
    self.listServ = DataShareServ;
    self.makeRequest = function() {
      self.listServ.request({
        hairColor: "red"
      });
    };
  });

  app.controller("gnomeList", function(DataShareServ) {
    var self = this;
    self.listServ = DataShareServ;
    self.listServ.request();
    self.list = self.listServ.data;
  });

  // Create the factory that share the Fact
  app.factory('DataShareServ', function($http) {
    var self = this;
    self.list = {};

    self.list.data = [];

    self.list.request = function(params) {
      var theUrl = 'https://gnome-shop-fl4m3ph03n1x.c9users.io/api/v1/gnomes';
      if (params.hairColor)
        theUrl = theUrl + "?hairColor=" + params.hairColor;

      $http({
        method: 'GET',
        url: theUrl,
        headers: {
          'Content-Type': 'application/json; charset=utf-8'
        }
      }).then(function successCallback(response) {
        self.list.data = response.data.entries;
        console.log("submitted");
      }, function errorCallback(response) {
        console.log('Error: ' + response);
      });
    };

    return self.list;
  });

})();

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>

<body>
  <!-- Search functionality -->
  <form ng-controller="gnomeFilter as filterCtrl" ng-submit="filterCtrl.makeRequest()">
    <button type="submit">Get Reddies !!</button>
  </form>

  <!-- Gnomes list -->
  <div ng-controller="gnomeList as listCtrl">
    <ul>
      <li ng-repeat="gnome in listCtrl.list">
        {{gnome.name}}
      </li>
    </ul>
  </div>
</body>


  1. 我的代码有什么问题?我该如何解决?


推荐答案

由于您要分配 gnomeList 控制器范围内的DataShareServ 中,您可以简单地遍历存储在服务中的数据,并在每个数据上对其进行更新和重新分配请求。这样,您不必处理在不同Controller上同步对象的问题。

Since you are assigning the DataShareServ to the scope of your gnomeList Controller, you could simply iterate over the Data which is stored in your service and which gets updated and reassigned on every request. This way you don't have to deal with syncing your objects on different Controllers.

这样,html看起来像这样:

This way, the html would look something like this:

<li ng-repeat="gnome in listCtrl.listServ.data">
   {{gnome.name}}
</li>

编辑

还要注意,您的代码中还有另一个问题。在 gnomeList 控制器中,您正在调用Service的 request 方法,该方法向某个端点发出异步请求并分配将其结果分配给局部变量,但是您不必等待将控制器变量分配给Service变量的结果。因此,用简单的话来说:

Also note, you have another Problem in your Code. In the gnomeList Controller, you are calling the request method of your Service which does an async request to some endpoint and assigns its result to a local variable, but you do not wait with assigning your controller variable to the result of the Service variable. So in simple Words:

self.list = self.listServ.data;

这将始终为空,因为http请求是异步的。您需要处理Promises(或类似的东西)。看看来自angular的 $ q 服务: https://docs.angularjs.org/api/ng/service/$q

this will always be empty because the http request is async. You need to deal with Promises (or something like that). Take a look at the $q Service from angular: https://docs.angularjs.org/api/ng/service/$q

请注意,如果您可以使用我的解决方案,只是想指出这一点。

Note that this would not be important if you would go with my solution, just wanted to point that out.

这篇关于使用Service AngularJs 1.6.1在控制器之间共享数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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