angularjs – 从服务器获取数据的推荐方法

前端之家收集整理的这篇文章主要介绍了angularjs – 从服务器获取数据的推荐方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在不使用$ resource的情况下,连接到AngularJS中的服务器数据源的推荐方法是什么。

$资源有很多限制,例如:

>不使用适当的期货
>不够灵活

有些情况下,$ resource可能不适合与后端通话。这显示如何设置$ resource like行为而不使用资源。
  1. angular.module('myApp').factory('Book',function($http) {
  2. // Book is a class which we can use for retrieving and
  3. // updating data on the server
  4. var Book = function(data) {
  5. angular.extend(this,data);
  6. }
  7.  
  8. // a static method to retrieve Book by ID
  9. Book.get = function(id) {
  10. return $http.get('/Book/' + id).then(function(response) {
  11. return new Book(response.data);
  12. });
  13. };
  14.  
  15. // an instance method to create a new Book
  16. Book.prototype.create = function() {
  17. var book = this;
  18. return $http.post('/Book/',book).then(function(response) {
  19. book.id = response.data.id;
  20. return book;
  21. });
  22. }
  23.  
  24. return Book;
  25. });

然后在你的控制器,你可以:

  1. var AppController = function(Book) {
  2. // to create a Book
  3. var book = new Book();
  4. book.name = 'AngularJS in nutshell';
  5. book.create();
  6.  
  7. // to retrieve a book
  8. var bookPromise = Book.get(123);
  9. bookPromise.then(function(b) {
  10. book = b;
  11. });
  12. };

猜你在找的Angularjs相关文章