从服务器获取数据的方式推荐 [英] Recommended way of getting data from the server
本文介绍了从服务器获取数据的方式推荐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
什么是连接到服务器AngularJS的数据源不使用推荐的方法 $资源
。
的 $资源
有许多限制,如:
- 不使用正确的期货
- 不存在足够的灵活性
解决方案
有说话时,后端时,$资源可能不适合的情况。这显示了如何建立这样的行为$资源,而无需使用资源。
angular.module('对myApp')。工厂('书',函数($ HTTP){
//书是我们可以使用检索类和
//更新服务器上的数据
VAR书=功能(数据){
angular.extend(此,数据);
} //一个静态方法来通过ID检索图书
Book.get =功能(ID){
返回$ http.get('/书/+ ID)。然后(功能(响应){
返回新的书(response.data);
});
}; //实例方法来创建一个新的图书
Book.prototype.create =功能(){
VAR书=这一点;
返回$ http.post('/书籍/',书)。然后(功能(响应){
book.id = response.data.id;
返回书;
});
} 返回书;
});
那么你的控制器中,您可以:
VAR的AppController =功能(书){
//创建一个图书
VAR书=新的图书();
book.name ='在简而言之AngularJS';
book.create(); //检索书
变种bookPromise = Book.get(123);
bookPromise.then(功能(B){
本书= B;
});
};
What is the recommended way to connect to server data sources in AngularJS without using $resource
.
The $resource
has many limitations such as:
- Not using proper futures
- Not being flexible enough
解决方案
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屋!
查看全文