Angular, Promises, ngResource

Angular, Promises, ngResource

本文关键字:ngResource Promises Angular      更新时间:2023-09-26

所以我很难让我的头脑被 angularJs 中的承诺所包裹。我已经混合了我的代码,试图对它进行一些蛮力/逆向工程理解,但没有任何可行的结论。

我的代码:正在回电以获取我管理的存储库列表。这些只是作为具有 id 和 url 的基本对象存储在数据库中。

这是我的看法。它允许我删除、查看和清除数据库中有关这些存储库的元数据。

<div class="container" ng-controller="adminCtrl as vm">
    <div class="row">
        <div class="col-sm-6 col-sm-offset-3">
            <label class="control-label" >Repos:</label>
            <div ng-repeat="repo in vm.repos">
                    <div class="clearfix">{{repo.URL}}<br>
                        <button class="btn btn-primary" ng-click='vm.listFiles(repo.URL)'>View Files</button>
                        <button class="btn btn-primary" ng-click='vm.clearFiles(repo.URL)'>Clear Files</button>
                        <button class="btn btn-primary" ng-click='vm.clearRepo(repo.URL)'>Delete Repo</button>
                    </div>
                    <br>
                </div>
            <label class="control-label" >Files:</label>
            <div ng-repeat="file in vm.files">
                <li>{{file.FullPath}}</li>
            </div>
        </div>
    </div>
    <!-- /.row -->
</div>

这是我的控制器,具有一些基本功能

(function (angular) {
'use strict';
var ngModule = angular.module('myApp.adminCtrl', []);
ngModule.controller('adminCtrl', function ($scope, $resource) {
    //"Global Variables"
    var File = $resource("/api/file/:repoUrl");
    var Repo_del = $resource("/api/repo/:repoUrl");
    var Repo = $resource("/api/repo");
    var vm = this;
    vm.files = [];
    vm.repos = [];
    vm.clearFiles = clearFiles;
    vm.listFiles = listFiles;
    vm.clearRepo = clearRepo;
    init();
    //Anything that needs to be instantiated on page load goes in the init
    function init() {
        listRepos();
    }
    function listRepos() {
        vm.repos = Repo.query();
    }
    //Lists all files 
    function listFiles(url) {
        vm.files = File.query({repoUrl: url});
    }
    function clearRepo(url) {
        Repo_del.remove({repoUrl: url});
    }
    function clearFiles(url) {
        File.remove({repoUrl: url});
    }
    });
}(window.angular));

现在这工作得很好,花花公子。它会带回存储库并列出它们。我可以使用所有功能删除、查看和删除。

当我尝试使列表项在删除时消失(而不是需要页面加载(时,出现了我的问题。为此,我需要在数组中找到要删除的项目的索引并将其删除。我打算使用一些lodash来做到这一点。看起来很简单。我的问题是,我的vm.repos阵列在控制器中不可用。

例如。当我尝试在 listRepos 函数中使用控制台日志打印出 vm.repos 时,如下所示

function listRepos() {
            vm.repos = Repo.query();
            console.log(vm.repos);
        }

我从控制台.log什么也没得到。所以这告诉我它没有被分配。这对我来说很奇怪,因为该列表显示在使用 vm.repos 的视图上的 ng-repeat 中。

当我能够打印出数组时,我也遇到了一个问题。它包含大量承诺信息。例如,如果我把控制台.log放在 init(( 函数中,我会得到一个数组,该数组在 Resource 对象下塞满了信息。

我不确定如何将其解析为可管理的对象。查看基本指南,我找到了一些示例,但没有任何东西可以转化为我的情况。

如何正确处理 api/资源承诺?


我遇到的另一个问题是能够在我的测试中模拟出所有 api 响应。这是我的下一个壮举。我不在乎它是否在这里得到解决,但我觉得它源于同样的问题。

这是我能够为这个控制器编写的唯一测试。

'use strict';
describe('adminCtrl', function () {
    beforeEach(function () {
        module('myApp.adminCtrl');
        module('myApp');

    });
    describe('listRepos()', function () {
        it('should return a json object representing a repository',
            inject(function (_$httpBackend_, $rootScope, $controller) {
                var scope = $rootScope.$new();
                var mockBackend = _$httpBackend_;
                var expectedResponse = {id: 12345, url: "https://github.com/myuser/myrepo.git"};
                mockBackend.expectGET('/api/repo').respond([expectedResponse]);
                var ctrl = $controller('adminCtrl', {$scope: scope});
                mockBackend.flush();
                expect(ctrl.repos.length).toEqual(1);
                console.log(ctrl.repos[0]);
                expect((angular.equals(ctrl.repos[0], expectedResponse)));
            }));
    });
});

对不起,如果这很多。希望这不是一个重复的问题。


编辑以显示我现在正在尝试的内容。

function clearRepo(url) {
        $http.delete('/api/repo/', {params: {repoUrl: url}}).then(function (){
            //DO THINGS
        });

表达:

app.delete('/api/repo/:repoUrl', repoCtrl.clear);

repoCtrl.clear

module.exports.clear = function (req, res) {
    var repoURL = req.params.repoUrl;
    //console.log(repoURL);
    Repo.remove({URL: repoURL}, function(err, results) {
        if (err) {
            console.log("ERR: " + err);
        } else {
            console.log(''n' + repoURL + ' repo deleted... 'n');
        }
    });

错误我得到:

DELETE http://localhost:3000/api/repo/?repoUrl=https:%2F%2Fgithub.com%2Fuw34%2Fmyrepo.git 404 (Not Found)

首先,承诺:

  • 由$http使用
  • 允许链接异步请求

像这样工作:

var promise = $http.get('/api/values');
promise.then(function(response) {
  $scope.displayData = response.data;
});
这是避免简单回调

的新方法(为什么要避免回调??检查这个 CallbackHell :)(


然而,回调可能很复杂,很难进行调试,每个人都喜欢编写同步代码。

为了简化起见,Angular 允许您编写看起来像同步代码的代码(但在内部,它是异步的(。要做到这一点,$resource封装一个承诺。

// this code return an empty array, then after received server respond, it will populate the empty array with data.
var values = VALUES.query();
// A simple version of it can be code like this
function simpleQuery() {
  var arrayReference = [];
  $http.get('api/values').then(function(response) {
    // populate array reference with data received from server
    angular.forEach(response.data, function(value) {
      arrayReference.push(value);
    });
    // after the return, angular run a $digest 
    // which will display all newly received data thank to biding on your view
  });
  return arrayReference ;
}

通过这样做,我返回一个空数组,该数组将在服务器响应中填充。

如果您愿意,可以从$resource那里获得承诺:

var promise = Repo.query().$promise;
promise.then(function(response) {
  $scope.displayData = response.data;
});

在2020年,你可能会使用Async/Await来代替$resource ;)

如果您想了解更多信息,请不要犹豫。