简体   繁体   English

Angular SPA与REST API的关系

[英]How Angular SPA relates to REST API

I'm newbie in node and I'm trying to understand how an Angular SPA, that have some states with uiRouter, can relates to an Express REST API to get data from an database. 我是Node的新手,我试图了解uiRouter具有某些状态的Angular SPA如何与Express REST API关联以从数据库获取数据。 Can anyone please take me an exemple? 任何人都可以请我为例吗?

Thanks 谢谢

An AugularJS SPA can talk to REST API through a variety of modules like $resource or a more complete library like Restangular AugularJS SPA可以通过$ resource等各种模块或诸如Restangular之类的更完整的库与REST API进行通信

Example with $resource $ resource示例

For example if your Express API can GET a user on /user/<userId> , and save it back through a POST , you can do this on AngularJS 例如,如果您的Express API可以在/user/<userId>GET用户,然后通过POST将其保存回去,则可以在AngularJS上执行此操作

var User = $resource('/user/:userId', {userId:'@id'});
var user = User.get({userId:123}, function() {
  user.abc = true;
  user.$save();
});

To understand what $resource will do on HTTP on each action refer to this default mapping 要了解$ resource对每个操作在HTTP上将执行的操作,请参考此默认映射

{ 'get':    {method:'GET'},
  'save':   {method:'POST'},
  'query':  {method:'GET', isArray:true},
  'remove': {method:'DELETE'},
  'delete': {method:'DELETE'} };

$http is low level (and built-upon by the REST client libraries) $ http是低级别的(由REST客户端库建立)

Another answer here suggested $http . 这里的另一个答案建议$http While it's entirely possible to do so, the REST libraries already build upon $http , to give you convenient support for the HTTP verbs and general REST facilities. 尽管完全有可能这样做,但是REST库已经基于$http构建,为您提供对HTTP动词和常规REST便利的方便支持。

If you use $http you'll have to do that manually (not to mention you won't be benefiting from the wisdom and best practices that went into building those libraries) 如果您使用$http ,则必须手动执行该操作(更不用说您将不会从构建这些库的智慧和最佳实践中受益)

I won't recommend to use $resource . 我不建议使用$resource It's the object that keeps link to the promise and when promise resolved it'll also contain data itself. 它是保持承诺的链接的对象,当承诺被解决时,它还将包含数据本身。 So if you want to do some actions when data comes you'll have to assing a callback to that promise anyway. 因此,如果您想在数据到来时执行一些操作,则无论如何都必须为该承诺设置一个回调。 Use $http instead. 请改用$http It's lower level angular abstraction for async requests. 它是异步请求的较低级别的角度抽象。 And here is the way you can use $http . 是使用$http

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM