javascript - 在 Controller 之间共享 1 个 ajax 响应

标签 javascript ajax angularjs

大局是——我很想在一个地方进行 ajax 调用并发送到我的所有 Controller (大约有 8 个),并根据字符串答案在所有 Controller 中设置显示/隐藏。这看起来很简单,但我在解决问题时遇到了一些麻烦。我能够弄清楚如何在 2 个 Controller 之间共享 json 对象,但这有点不同,所以我想也许我正在以不正确的方式应用对我有用的先前逻辑。

我建立了一个工厂来像这样在所有 Controller 之间共享

.factory('statusCheck', ['$http', function ($http) {

var currentId = self.location.search;
if(currentId[0] === "?"){
    currentId = currentId.slice(1);
}
 var stats = $http({
        method: "GET",
        url: "/getLessonDetails/" + currentId
    })
    .success(function(data, status, headers, config){

    return data.status;
    });

return stats;

}])

我在这里要做的就是让它执行 ajax 调用(您可以忽略 currentId 部分)并返回 data.status。然后我在每个 Controller 中注入(inject) statusCheck 并使用它。

一旦我将 statusCheck 作为正确的字符串值返回(data.status 将等于 3 个字符串中的 1 个),我想在 Controller 中使用它来显示/隐藏内容。我已经在每个名为 $scope.editorEnabled 的 Controller 中设置了一个范围 bool 值,它在我想要的显示/隐藏之间切换(如果设置为 true 或 false。

所以一旦我在 Controller 中有了 statusCheck 我想检查它的值并在 Controller 中做这样的事情 -

 if(statusCheck == "On"){
 $scope.editorEnabled = true;
 }else if(statusCheck == "Off"){
  $scope.editorEnabled = false;
 }else if(statusCheck == "ViewOnly"){
   $scope.editorEnabled = false;
   $scope.viewOnlyMode= true;
 }

我什至不知道我的工厂是否正常工作,但当它正常工作时,我想确保在它尝试读取 Controller 中的这些 if 语句之前我得到了 ajax get 的字符串,因为它们没有包装在任何东西都会立即开火。我不知道这种想法是否适合 Angular,我仍在调整自己以适应它的过程。任何建议将不胜感激。感谢阅读!

最佳答案

当 http promise 被解析时,您可以在工厂返回服务中设置一个属性,并观察 Controller 中属性的变化;

.factory('statusCheck', ['$http', function ($http) {
    var me = {
        status: 0
    };

    var currentId = self.location.search;
    if(currentId[0] === "?"){
      currentId = currentId.slice(1);
    }

    $http({
        method: "GET",
        url: "/getLessonDetails/" + currentId
    })
    .success(function(data, status, headers, config){
       me.status = data.status;
    });

    return me;
}]);

在你的 Controller 中,观察 statusCheck.status 的变化并做任何你想做的事

 $scope.statusCheck = statusCheck;

 $scope.$watch('statusCheck.status', function (newValue) {
       if(newValue == "On"){
          $scope.editorEnabled = true;
       }else if(newValue == "Off"){
          $scope.editorEnabled = false;
       }else if(newValue == "ViewOnly"){
         $scope.editorEnabled = false;
         $scope.viewOnlyMode= true;
       }
 });

关于javascript - 在 Controller 之间共享 1 个 ajax 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25767228/

相关文章:

javascript - 这个 es6 语法叫什么?

javascript - 欺骗用户代理的 Safari 扩展?

javascript - 对象中的返回函数不起作用

c# - 无法处理消息,因为内容类型 'application/json; charset=utf-8' 不是预期的类型 'text/xml; charset=utf-8'

javascript - Chrome 的 AngularJS 和 Symfony 3 CORS 问题

javascript - this.state 在 react native 的 onPress 事件期间未定义

javascript - JS/AJAX - 显示来自 json 的正确消息

jQuery:通过ajax加载的内容可以更新DOM吗?

javascript - 以 Angular/ ionic 方式刷新后退按钮上的页面

javascript - 测试-尝试使用 $httpBackend.expectGET 通过用户名获取用户 JSON 对象