Order of executing requests with AngularJS's n

2019-09-18 18:38发布

问题:

This is a follow-up question to Part1.

Part 2:

books_ctrl.js.coffee

myApp.controller "BooksCtrl", ($scope, Book) ->
  $scope.save = () ->
    if $scope.book.id?
      Book.update($scope.book)
    else
      Book.save($scope.book)
    $scope.book = {}
    $scope.getBooks()

book.js.coffee

myApp.factory "Book", ($resource) ->
  $resource("/books/:id", {id: "@id"}, {update: {method: "PUT"}})

Rails Server Development Log

Started GET "/books" for 127.0.0.1 at 2014-07-03 12:53:07 +0200
Processing by BooksController#index as JSON
  Book Load (0.0ms)  SELECT "books".* FROM "books"
Completed 200 OK in 2ms (Views: 2.0ms | ActiveRecord: 0.0ms)


Started POST "/books" for 127.0.0.1 at 2014-07-03 12:53:07 +0200
Processing by BooksController#create as JSON
  Parameters: {"title"=>"Test", "author"=>"Tester", "book"=>{"title"=>"Test", "author"=>"Tester"}}
   (0.0ms)  begin transaction
  SQL (1.0ms)  INSERT INTO "books" ("author", "created_at", "title", "updated_at") VALUES (?, ?, ?, ?)  [["author", "Tester"], ["created_at", "2014-07-03 10:53:07.627400"], ["title", "Test"], ["updated_at", "2014-07-03 10:53:07.627400"]]
   (23.0ms)  commit transaction
Completed 200 OK in 29ms (Views: 1.0ms | ActiveRecord: 24.0ms)

Here is my problem: AngularJS seems to execute all requests at the same time. That way the GET-Request is executed prior to the POST-Request, an undesirable effect in my case.

How can I tell Angular to execute the GET only after POST is completed?

回答1:

You can do:

Book.save($scope.book, $scope.getBooks)

Or:

Book.save($scope.book).$promise.then($scope.getBooks)