Angular 控制器可以有多个 $resource 吗?

Can an Angular controller have multiple $resource?

我有一个 angular 控制器,它使用 $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
    };
});

就像你已经做的那样,让另一个工厂创建一个新的 $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;
         });

    };
});

相关资源始终可以在工厂中组合在一起。

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

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

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