简体   繁体   中英

$resource function wrapper angularjs

Currently, I'm doing things like this:

var albumList = $resource('https://api.imgur.com/3/account/guy123/albums').get(function () {
    albumList.data.forEach(function (album) {
        albums.push(album);
    });
});

How do I turn that into a function that I can call in both my service and controller like:

factory('Imgur', function($resource, $http) {
    var albumsService = {};
    var albums = [];

    albumsService.getAlbumList = function() {
        var albumList = $resource('https://api.imgur.com/3/account/guy123/albums').get(function () {
            albumList.data.forEach(function (album) {
                albums.push(album);
            });
        });
    };

    albumsService.albumList = function() {
        albumsService.getAlbumList();
        return albums;
    };

    return albumsService;
});


.controller('Filters', ['$scope','Imgur', function($scope, Imgur) {
    $scope.imgur = Imgur;
    $scope.imgur.albumList();
    //OR
    $scope.imgur.getAlbumList();

    //Some good context here is what if a user wanted to "refresh" the data.
    $scope.updateFilter = function() {
        $scope.imgur.getAlbumList();
    }; 


}]);

Ultimately the goal here is to be able to call a resource service as many times as I want. The service should be a function callable by both inside the service and inside the controller.

angular.module("MyApp", ['ng-resource']).
  service("Database", function() {
    return {
      albums : $resource('https://api.imgur.com/3/account/guy123/albums')
    }
  }).
  controller("MyCtrl", function(Database) {
    $scope.albums = Database.albums.query();
  })

Then in your Html

<html ng-app="MyApp">
<head></head>
<body ng-controller="MyCtrl">
  <ul>
    <li ng-repeat="album in albums">
      {{album.name}}
    </li>
  </ul>
</body> 
</html>

The Service

var service = angular.module("yourApp.service", ['ngResource']);
service.factory('albumsService', [$resource',function ($resource){
    return $resource('https://api.imgur.com/3/account/guy123/albums',{},{
         query: {method: "GET", isArray:true}
    });
}]);

Then in the controller

$scope.albumList = albumsService.query();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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