【问题标题】:Can an Angular controller have multiple $resource?一个 Angular 控制器可以有多个 $resource 吗?
【发布时间】:2015-01-10 08:37:49
【问题描述】:

我有一个使用 $resource 实例化的角度控制器(例如 /rest/book),它工作正常。

我正在考虑允许控制器使用另一个 $resource(例如 /rest/recommendedTitle),但我不确定如何。

这是我的控制器当前的样子:

var dashboard = angular.module('dashboard', ['ngResource', 'ngRoute']);

dashboard.factory("Post", function($resource) {
    return $resource("/rest/book/:id");
});

dashboard.controller("DashboardCtrl", function($scope, Post) {
    // handle retriving a list
    Post.query(function(data) {
        $scope.books = data;
    });

    // user selected on a book
    $scope.bookSelectionListener = function(book) {
        $scope.selectedBook = book;

        console.log("Selected book id: " + $scope.selectedBook.bookId.S);

        console.log("Going to fetch similar titles which is in another table based on the book id");

         // call another $resource restful api to get recommended title
    };
});

【问题讨论】:

  • 当然。只需创建另一个工厂。
  • 是的。但我会更好地命名你的工厂。一种称为“Books”,一种称为“RecommendedTitles”而不是“Post”。然后他们会像你所做的那样将 api url 传递给每个工厂的 $resource
  • @WayneEllery 明白了,谢谢。

标签: angularjs express angular-resource


【解决方案1】:

相关资源总是可以在工厂中组合在一起。

dashboard.factory("Post", function($resource) {
    return {
           books:$resource("/rest/book/:id"),
           recommendedTitles:$resource("/rest/recommendedTitles")
    };
});

然后在控制器中,可以使用资源:

Post.books.query()
Post.recommendedTitles.query()

【讨论】:

    【解决方案2】:

    就像你已经做的那样,让另一个工厂创建一个新的$resource 并将其注入你的控制器:

    var dashboard = angular.module('dashboard', ['ngResource', 'ngRoute']);
    
    dashboard.factory("Post", function($resource) {
        return $resource("/rest/book/:id");
    });
    
    dashboard.factory("Whatever", function($resource) {
        // you should probably initialize some particular method depending on your backend here
        return $resource("/rest/whatever/:id");
    });
    
    dashboard.controller("DashboardCtrl", function($scope, Post, Whatever) {
        // handle retrieving a list
        Post.query(function(data) {
            $scope.books = data;
        });
    
        // user selected on a book
        $scope.bookSelectionListener = function(book) {
            $scope.selectedBook = book;
    
            console.log("Selected book id: " + $scope.selectedBook.bookId.S);
    
            console.log("Going to fetch similar titles which is in another table based on the book id");
    
             // call another $resource restful api to get recommended title
    
             Whatever.query({bookId : book.id}, function(data) {
                 $scope.similarBooks = data;
             });
    
        };
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-04
      • 1970-01-01
      • 1970-01-01
      • 2017-09-30
      • 1970-01-01
      • 2012-03-06
      • 2012-07-18
      • 1970-01-01
      相关资源
      最近更新 更多