从服务器获取数据的推荐方式 [英] Recommended way of getting data from the server

查看:23
本文介绍了从服务器获取数据的推荐方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在不使用 $resource 的情况下,在 AngularJS 中连接到服务器数据源的推荐方法是什么.

What is the recommended way to connect to server data sources in AngularJS without using $resource.

$resource 有很多限制,例如:

  1. 未使用正确的期货
  2. 不够灵活

推荐答案

有些情况下 $resource 在与后端交谈时可能不合适.这展示了如何在不使用资源的情况下设置类似 $resource 的行为.

There are cases when $resource may not be appropriate when talking to backend. This shows how to set up $resource like behavior without using resource.

angular.module('myApp').factory('Book', function($http) {
  // Book is a class which we can use for retrieving and 
  // updating data on the server
  var Book = function(data) {
    angular.extend(this, data);
  }

  // a static method to retrieve Book by ID
  Book.get = function(id) {
    return $http.get('/Book/' + id).then(function(response) {
      return new Book(response.data);
    });
  };

  // an instance method to create a new Book
  Book.prototype.create = function() {
    var book = this;
    return $http.post('/Book/', book).then(function(response) {
      book.id = response.data.id;
      return book;
    });
  }

  return Book;
});

然后在您的控制器中,您可以:

Then inside your controller you can:

var AppController = function(Book) {
  // to create a Book
  var book = new Book();
  book.name = 'AngularJS in nutshell';
  book.create();

  // to retrieve a book
  var bookPromise = Book.get(123);
  bookPromise.then(function(b) {
    book = b;
  });
};

这篇关于从服务器获取数据的推荐方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆