Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REST getting single item - get is not a function

Tags:

angularjs

I'm learning AngularJS from :

https://docs.angularjs.org/tutorial/step_13

But using my own example. After 13 step chrome console gives me an error

Book.get is not a function

in this controller :

angular.module('bookDetail').component(
    'bookDetail',
    {
        templateUrl : 'book-detail/book-detail.template.html',
        controller : [ '$routeParams', 'Book',
                function BookDetailController(Book, $routeParams) {
                    var self = this;

                    self.book = Book.get({
                        bookId : $routeParams.bookId
                    }, function(book) {
                        self.setTitle(book.title);
                    });

                    self.setTitle = function setTitle(title) {
                        self.mainTitle = title;
                    }
                } ]
    });

controller that works:

angular.module('bookList').component('bookList', {
templateUrl : 'book-list/book-list.template.html',
controller : [ 'Book', function BookListController(Book) {
    this.books = Book.query();
} ]
});

and the service:

 angular.module('core.book').factory('Book', [ '$resource', function($resource) {
return $resource('books/:bookId.json', {}, {
    query : {
        method : 'GET',
        params : {
            bookId : 'books'
        },
        isArray : true
    }
});
} ]);

I have no clue what's wrong here.

like image 759
egzaell Avatar asked Mar 03 '26 01:03

egzaell


1 Answers

Your Dependency injection is swapped.

  controller : [ '$routeParams', 'Book',
            function BookDetailController(Book, $routeParams) {

The array of string parameters to be passed into the function are matched up in order by position, not by name. The variable names can be anything arbitrary. So in this case, you are taking an instance of $routeParams and assigning it to the Book variable, and visa versa.

Switching the order of the injections should correct the issue:

  controller : [ '$routeParams', 'Book',
            function BookDetailController($routeParams, Book) {
like image 138
Claies Avatar answered Mar 07 '26 11:03

Claies