An AngularJS 1.x WebSocket service for connecting client applications to servers.
You can download angular-websocket by:
bower install angular-websocket --save
npm install angular-websocket --save
https://cdn.rawgit.com/AngularClass/angular-websocket/v2.0.0/dist/angular-websocket.js
https://cdn.rawgit.com/AngularClass/angular-websocket/v2.0.0/dist/angular-websocket.min.js
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script src="bower_components/angular-websocket/angular-websocket.js"></script>
<section ng-controller="SomeController">
<ul ng-repeat="data in MyData.collection track by $index" >
<li> {{ data }} </li>
</ul>
</section>
<script>
angular.module('YOUR_APP', [
'ngWebSocket' // you may also use 'angular-websocket' if you prefer
])
// WebSocket works as well
.factory('MyData', function($websocket) {
// Open a WebSocket connection
var dataStream = $websocket('ws://website.com/data');
var collection = [];
dataStream.onMessage(function(message) {
collection.push(JSON.parse(message.data));
});
var methods = {
collection: collection,
get: function() {
dataStream.send(JSON.stringify({ action: 'get' }));
}
};
return methods;
})
.controller('SomeController', function ($scope, MyData) {
$scope.MyData = MyData;
});
</script>
$websocket
(in module ngWebSocket
)returns instance of $Websocket
name | arguments | description |
---|---|---|
$websocket constructor |
url:String | Creates and opens a WebSocket instance. var ws = $websocket('ws://foo'); |
send | data:String,Object returns | Adds data to a queue, and attempts to send if socket is ready. Accepts string or object, and will stringify objects before sending to socket. |
onMessage | callback:Function options{filter:String,RegExp, autoApply:Boolean=true} |
Register a callback to be fired on every message received from the websocket, or optionally just when the message's data property matches the filter provided in the options object. Each message handled will safely call $rootScope.$digest() unless autoApply is set to `false in the options. Callback gets called with a MessageEvent object. |
onOpen | callback:Function | Function to be executed each time a socket connection is opened for this instance. |
onClose | callback:Function | Function to be executed each time a socket connection is closed for this instance. |
onError | callback:Function | Function to be executed each time a socket connection has an Error for this instance. |
close | force:Boolean:optional | Close the underlying socket, as long as no data is still being sent from the client. Optionally force close, even if data is still being sent, by passing true as the force parameter. To check if data is being sent, read the value of socket.bufferedAmount . |
name | type | description |
---|---|---|
socket | window.WebSocket | WebSocket instance. |
sendQueue | Array | Queue of send calls to be made on socket when socket is able to receive data. List is populated by calls to the send method, but this array can be spliced if data needs to be manually removed before it's been sent to a socket. Data is removed from the array after it's been sent to the socket. |
onOpenCallbacks | Array | List of callbacks to be executed when the socket is opened, initially or on re-connection after broken connection. Callbacks should be added to this list through the onOpen method. |
onMessageCallbacks | Array | List of callbacks to be executed when a message is received from the socket. Callbacks should be added via the onMessage method. |
onErrorCallbacks | Array | List of callbacks to be executed when an error is received from the socket. Callbacks should be added via the onError method. |
onCloseCallbacks | Array | List of callbacks to be executed when the socket is closed. Callbacks should be added via the onClose method. |
readyState | Number:readonly | Returns either the readyState value from the underlying WebSocket instance, or a proprietary value representing the internal state of the lib, e.g. if the lib is in a state of re-connecting. |
initialTimeout | Number | The initial timeout, should be set at the outer limits of expected response time for the service. For example, if your service responds in 1ms on average but in 10ms for 99% of requests, then set to 10ms. |
maxTimeout | Number | Should be as low as possible to keep your customers happy, but high enough that the system can definitely handle requests from all clients at that sustained rate. |
This type is returned from the send()
instance method of $websocket, inherits from $q.defer().promise.
name | arguments | description |
---|---|---|
cancel | Alias to deferred.reject() , allows preventing an unsent message from being sent to socket for any arbitrary reason. |
|
then | resolve:Function, reject:Function | Resolves when message has been passed to socket, presuming the socket has a readyState of 1. Rejects if the socket is hopelessly disconnected now or in the future (i.e. the library is no longer attempting to reconnect). All messages are immediately rejected when the library has determined that re-establishing a connection is unlikely. |
$websocketBackend
(in module ngWebSocketMock
)Similar to httpBackend
mock inAngularJS's ngMock
module. You can use ngWebSocketMock
to mock a websocketserver in order to test your applications:
var $websocketBackend;
beforeEach(angular.mock.module('ngWebSocket', 'ngWebSocketMock');
beforeEach(inject(function (_$websocketBackend_) {
$websocketBackend = _$websocketBackend_;
$websocketBackend.mock();
$websocketBackend.expectConnect('ws://localhost:8080/api');
$websocketBackend.expectSend({data: JSON.stringify({test: true})});
}));
name | arguments | description |
---|---|---|
flush | Executes all pending requests | |
expectConnect | url:String | Specify the url of an expected WebSocket connection |
expectClose | Expect "close" to be called on the WebSocket | |
expectSend | msg:String | Expectation of send to be called, with required message |
verifyNoOutstandingExpectation | Makes sure all expectations have been satisfied, should be called in afterEach | |
verifyNoOutstandingRequest | Makes sure no requests are pending, should be called in afterEach |
$ npm install
$ bower install
$ npm test
Run karma in Chrome, Firefox, and Safari
In the project root directory open index.html
in the example folder or browserify example
$ npm run dist
Builds files with uglifyjs
Contact us anytime for anything about this repo or Angular 2
enjoy — AngularClass
Learn AngularJS, Angular 2, and Modern Web Development form the best.Looking for corporate Angular training, want to host us, or Angular consulting? patrick@angularclass.com
Title {{ data }} var app = angular.module('myApp', ['ngWebSocket']) .factory('MyData', function ($websocket) { // Open a WebSocket connection var dataStream = $websocket('ws://118.145.23.94/rwservice'
Angular Websocket教程 在本教程中,我们将介绍如何实现一个非常简单的基于WebSocket的Angular应用程序。本教程版本: angular ^6.1.0 rxjs ^6.0.0 浏览器兼容性 在这个时候,我认为让你知道websocket浏览器的兼容性不是100%,一些旧的浏览器可能不支持WebSockets是个好主意。因此,如果您暂时没有更新,本教程可能无法在您的浏览器中运行
这篇文章给大家介绍的文章内容是关于angular如何使用websocket的方法介绍,有很好的参考价值,希望可以帮助到有需要的朋友。 对于开始接触websocket的人来说,实在是太难了。而且一路上的坑还不少。 网上有很多关于websocket的文章和插件,老码找了很多之后还是觉得这个插件不错,对于使用angularjs开发的朋友,我很推荐这个 angular websocket.js 这个有比较
/** * websocket服务 */ import {HttpClient} from '@angular/common/http'; import {Injectable} from '@angular/core'; import {Observable} from "rxjs"; import {Subject} from 'rxjs'; import {BaseService} fr
使用这个: https://www.cnblogs.com/fengguohoudejiyi/p/8531542.html wesocket.service.ts import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; @Injectable() export class WebSocketSer
Based on https://github.com/AngularClass/angular-websocket and migrated to Angular2 Installation npm install angular2-websocket Usage: import {$WebSocket} from 'angular2-websocket/angular2-websocket'
1.npm下载: npm install angular2-websocket 2.需要在哪个组件使用就在那里引入: import {$WebSocket} from 'angular2-websocket/angular2-websocket' 3.具体的使用看以下代码: 1 sendMsg() { 2 //新建连接 3 var ws = new $WebS
angular 前端 写一个websocket服务 src/app/service/websocket.service.ts import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { Subject } from 'rxjs'; @Injectable({ providedI
因为需要使用WebSocket做TCP的长连接,网上搜了socket.io没找到合适的解决方案。就用原生的了。 贴代码: 先写一个工具类 import { Injectable } from '@angular/core'; import { Observable } from "rxjs/Observable"; import {observable} from "rxjs/symbol/o
对于开始接触websocket的人来说,实在是太难了。而且一路上的坑还不少。 网上有很多关于websocket的文章和插件,老码找了很多之后还是觉得这个插件不错,对于使用angularjs开发的朋友,我很推荐这个 angular websocket.js 这个有比较全的开发文档和使用指导,可以实现socket意外中断自动恢复连接等功能。 下面是我的项目中使用的websocket, 先在项目中引进w
前言 最近在项目中需要使用到websocket进行前后端通信,由此我们将讨论如何使用WebSocket和RxJS在Angular应用程序中实现此功能。 一、Websocket是什么? WebSocket 协议在2008年诞生,2011年成为国际标准。所有浏览器都已经支持了。 它的最大特点就是,服务器可以主动向客户端推送信息,客户端也可以主动向服务器发送信息,是真正的双向平等对话,属于服务器推送技术
websocket 上篇链接: angular中websocket前后帧数据对比 websocket 请求与订阅 import { Component, OnInit, OnDestroy} from '@angular/core'; import { CrrcBaseWebSocketService } from '@shared/services/http-services/crrc-base
Angular使用RxJS,它本质上是一个反应式扩展的javascript实现。这是一个使用可观察序列组成异步和基于事件的程序的库,非常适合使用WebSockets。 简而言之,RxJS允许我们从websocket连接中侦听新消息,然后在“X”事件发生时执行操作。这方面的一个例子可以是实时聊天应用程序。假设我们有3个人连接到我们的聊天应用程序,其中一个人发送消息。如果我们想在收到消息时在应用程序中
Error during WebSocket handshake: Unexpected response code: 200 错误解决 之前项目中是用的是soket.js实现前端与后台soket服务实现连接没有问题,后来因为项目需引入微信小程序同样需要通过websoket方式连接,结果通过小程序提供的wx.connectSocket()方式连接时一直报 Error during WebSocke
在angular7中,cli已经自动配置了websocket,不用再次进行安装 第一种websocket,没使用订阅,有断线重连的功能 1.创建一个WebsocketService ws:WebSocket; url="ws://127.0.0.1:25555"; lockReconnect:boolean; constructor() { } createObserv
Angular 是一款十分流行且好用的 Web 前端框架,目前由 Google 维护。这个条目收录的是 Angular 2 及其后面的版本。由于官方已将 Angular 2 和之前的版本 Angular.js 分开维护(两者的 GitHub 地址和项目主页皆不相同),所以就有了这个页面。传送门:Angular.js 特性 跨平台 渐进式 Web 应用 借助现代化 Web 平台的力量,交付 app
问题内容: 我目前正在玩一个使用websocket与后端通信的有角度的应用程序。我在使angular的数据绑定正常工作时遇到了一些麻烦。 在下面的示例中,我创建了一个服务,该服务创建了websocket连接。如果websocket收到一条消息,我只需将该消息推送到包含所有收到消息的数组中即可。 在我的控制器中,我将该消息数组绑定到作用域,然后用于在我的局部视图中列出所有消息。 服务: 控制器: 部
即将到来的Angular 2框架是使用TypeScript开发的。 因此Angular和TypeScript一起使用非常简单方便。 Angular团队也在其文档里把TypeScript视为一等公民。 正因为这样,你总是可以在Angular 2官网(或Angular 2官网中文版)里查看到最新的结合使用Angular和TypeScript的参考文档。 在这里查看快速上手指南,现在就开始学习吧!
从头开始创建项目 lint你的代码 运行您的单元测试和端到端测试。 Angular 2 CLI目前只在TypeScript中生成框架,稍后还会有其他版本。
这小节内容是译者加的,因为我认为对于新手而言,学习一个框架是有成本的,特别是对于一个不算简单的技术来说,我希望这篇教程是对新手友好的,所以我首先要让你放心的将时间和精力投入到Angular2 中。那我们先不谈技术细节,先用数据说话。 这里我多说一句,最近看一些文章中谷歌趋势截图,大都没有把范围限定在“编程”上。图中可以看出Vue2非常少,所以在下面比较中不再单独统计。 教程数量 这里我选取的主要是
我们已经在Highcharts Configuration Syntax一章中看到了用于绘制图表的配置 。 下面给出角度计图表的示例。 配置 (Configurations) 现在让我们看一下所采取的其他配置/步骤。 chart.type 将图表类型配置为基于计量。 将类型设置为“规格”。 var chart = { type: 'guage' }; pane 此类型仅适用于极坐标图和角度