Javascript 超越 AngularJS 和 WebSockets

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26299403/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:41:27  来源:igfitidea点击:

AngularJS and WebSockets beyond

javascriptangularjswebsocketsocket.io

提问by Diogo Barroso

I just read this post, and I do understand what the difference is. But still in my head I have the question. Can/Should I use it in the same App/Website? Say I want the AngularJs to fetch content and update my page, connecting to a REST api and all of that top stuff. But on top of that I also want a realtime chat, or to trigger events on other clients when there is an update or a message received.

我刚刚阅读了这篇文章,我确实明白其中的区别。但我的脑海里仍然有这个问题。我可以/应该在同一个应用程序/网站中使用它吗?假设我希望 AngularJs 获取内容并更新我的页面,连接到 REST api 和所有最重要的东西。但最重要的是,我还想要实时聊天,或者在收到更新或消息时触发其他客户端上的事件。

Does Angular support that? Or I need to use something like Socket.io to trigger those events? Does it make sense to use both? If someone could help me or point me to some good reading about that if there is a purpose for using both of them together.

Angular 支持吗?或者我需要使用 Socket.io 之类的东西来触发这些事件?两者同时使用有意义吗?如果有人可以帮助我或向我指出一些关于这方面的好书,是否有将它们一起使用的目的。

Hope I'm clear enough. thank you for any help.

希望我足够清楚。感谢您的任何帮助。

采纳答案by vtortola

Javascript supports WebSocket, so you don't need an additional client side framework to use it. Please take a look at this $connection servicedeclared in this WebSocket based AngularJS application.

Javascript 支持 WebSocket,因此您不需要额外的客户端框架来使用它。请看一下这个基于 WebSocket 的 AngularJS 应用程序中声明的$connection 服务

Basically you can listen for messages:

基本上你可以收听消息:

   $connection.listen(function (msg) { return msg.type == "CreatedTerminalEvent"; }, 
        function (msg) {
            addTerminal(msg);
            $scope.$$phase || $scope.$apply();
   });

Listen once (great for request/response):

听一次(非常适合请求/响应):

    $connection.listenOnce(function (data) {
        return data.correlationId && data.correlationId == crrId;
    }).then(function (data) {
        $rootScope.addAlert({ msg: "Console " + data.terminalType + " created", type: "success" });
    });

And send messages:

并发送消息:

    $connection.send({
        type: "TerminalInputRequest",
        input: cmd,
        terminalId: $scope.terminalId,
        correlationId: $connection.nextCorrelationId()
    });

Usually, since a WebSocket connection is bidirectional and has a good support, you can also use it for getting data from the server in request/response model. You can have the two models:

通常,由于 WebSocket 连接是双向的并且具有良好的支持,因此您也可以使用它从请求/响应模型中的服务器获取数据。你可以有两个模型:

  • Publisher/Subscriber: Where the client declares its interest in some topics and set handlers for messages with that topic, and then the server publish (or push) messages whenever it sees fit.

  • Request/response: Where the client sends a message with a requestID (or correlationId), and listen for a single response for that requestId.

  • 发布者/订阅者:客户端声明它对某些主题感兴趣并为该主题的消息设置处理程序,然后服务器在它认为合适的时候发布(或推送)消息。

  • 请求/响应:客户端发送带有 requestID(或correlationId)的消息,并侦听该 requestId 的单个响应。

Still, you can have both if you want, and use REST for getting data, and WebSocket for getting updates.

尽管如此,如果您愿意,您可以同时拥有两者,并使用 REST 获取数据和 WebSocket 获取更新。

In server side, you may need to use Socket.io or whatever server side framework in order to have a backend with WebSocket support.

在服务器端,您可能需要使用 Socket.io 或任何服务器端框架,以便拥有支持 WebSocket 的后端。

回答by JeremyE

As noted in the answerin your linked post, Angular does not currently have built-in support for Websockets. So, you would need to directly use the Websockets API, or use an additional library like Socket.io.

正如您链接的帖子中的答案所述,Angular 目前没有对 Websockets 的内置支持。因此,您需要直接使用 Websockets API,或者使用像 Socket.io 这样的附加库。

However, to answer your question of if you should use both a REST api and Websockets in a single Angular application, there is no reason you can't have both standard XmlHttpRequest requests for interacting with a REST api, using $http or another data layer library such as BreezeJS, for certain functionality included in various parts of the application and also use Wesockets for another part (e.g. real time chat).

但是,要回答您是否应该在单个 Angular 应用程序中同时使用 REST api 和 Websockets 的问题,您没有理由不能同时使用标准 XmlHttpRequest 请求与 REST api 进行交互,使用 $http 或其他数据层库,例如 BreezeJS,用于应用程序各个部分中包含的某些功能,并在另一部分(例如实时聊天)中使用 Wesockets。

Angular is designed to assist with handling this type of scenario. A typical solution to would be to create one or more controllers to handle the application functionality and update your page and then creating separate Services or Factories that encapsulate the data management of each of your data end points (i.e. the REST api and the realtime chat server), which are then injected into the Controllers.

Angular 旨在帮助处理此类场景。一个典型的解决方案是创建一个或多个控制器来处理应用程序功能并更新您的页面,然后创建单独的服务或工厂来封装每个数据端点的数据管理(即 REST api 和实时聊天服务器),然后将它们注入到控制器中。

There is a great deal of information available on using angular services/factories for managing data connections. If you're looking for a resource to help guide you on how to build an Angular application and where data services would fit in, I would recommend checking out John Papa's AngularJS Styleguide, which includes a section on Data Services.

有大量关于使用 Angular 服务/工厂来管理数据连接的信息。如果您正在寻找一种资源来帮助指导您如何构建 Angular 应用程序以及数据服务适合的位置,我建议您查看 John Papa 的AngularJS 样式指南,其中包含有关数据服务的部分。

For more information about factories and services, you can check out AngularJS : When to use service instead of factory

有关工厂和服务的更多信息,您可以查看AngularJS:何时使用服务而不是工厂