AngularJS可以在没有REST API的情况下使用吗? [英] Can AngularJS be used without a REST API?

查看:95
本文介绍了AngularJS可以在没有REST API的情况下使用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用node.js创建一个简单的网站时,我可以使用视图引擎(例如.jade)和为其提供数据的控制器(例如简单的待办事项列表)。但是,如果我决定将AngularJS添加为客户端框架,那么我似乎必须在后端实现REST API以从中获取数据。几乎所有我在线使用AngularJS看到的例子都有这个基本架构:客户端(angular)通过REST API与服务器通信。

When I am creating a simple website with node.js I am fine with using the view engine (eg. jade) and controllers that provide data to it (eg. simple todo list). However, if I decide to add AngularJS as the client framework then it seems that I must implement REST API on the backend to get data from it. Almost all examples I see online with AngularJS have this basic architecture: client (angular) communicates with the server via REST API.

可以在没有REST API的情况下使用AngularJS,如果是这样,我应该这样做还是应该避免使用它?在没有REST API后端的情况下使用AngularJS是否有任何建议/最佳实践?

Can AngularJS be used without REST API and if so should I do it or should avoid it? Are there any recommendation/best practices for using AngularJS without REST API backend?

推荐答案

绝对正确。即使您从未使用 $ http 与您的服务器通信的服务。您仍然可以利用这些实用程序来帮助管理您的DOM。

Absolutely. Angular can still do a lot on your site even if you never utilize the $http service to talk to your server. You can still take advantage of the utilities for helping out with managing your DOM.

也就是说,大多数现代应用程序需要从服务器获取数据。您可能需要这么做的原因很多。例如,如果您有需要注册的用户,那么您需要在某处存储用户名和密码。那个地方将在只有你的服务器可以访问的数据库中。然后你的服务器会提供一些你可以通过Angular的 $ http 服务与之交谈的网址。

That said, most modern apps need to get data from the server. There are tons of reasons why you might need to do this. For example, if you had users that needed to sign up then you'd need to store their username and password somewhere. That somewhere would be in a database that only your server can access. Then your server would provide some URLs that you can talk to via Angular's $http service.

如果你有的话一个应用程序调用服务器,但你想关闭网络通信进行测试,你可以 mock $ http 呼叫响应。 Angular为此目的提供了 $ httpBackend 。您可以使用它来设置虚假URL,假装响应您的 $ http 调用,以便您的 $ http 调用不知道他们实际上是在和服务器说话。

If you do have an app that makes calls to the server but you want to turn off the network communication for testing, you can mock the $http call responses. Angular provides an $httpBackend for that exact purpose. You can use it to set up dummy URLs that pretend to respond to your $http calls so that your $http calls don't know they aren't actually talking to a server.

authRequestHandler = $httpBackend.when('GET', '/auth.py')
                       .respond({userId: 'userX'}, {'A-Token': 'xxx'});

在测试期间没有REST后端测试代码是完美的。

Perfect for testing your code without a REST backend during testing.

这篇关于AngularJS可以在没有REST API的情况下使用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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