afrad / angular2-websocket Goto Github PK
View Code? Open in Web Editor NEWWebsocket wrapper for angular2 based on angular-websocket
License: Apache License 2.0
Websocket wrapper for angular2 based on angular-websocket
License: Apache License 2.0
new version npm pls thanks
Hello, thank you for this piece of code adding to angular2 however I have problem as it says require is not defined, and when I add require, the angular stops to work. What can i do?
Hi, method onOpen and onClose not working, this is my code.
` this.webSocket = new $WebSocket("ws://localhost:8000");
console.log("Conectando");
this.webSocket.onMessage(function(message) {
console.log(message.data);
}, null);
this.webSocket.onOpen(function() {
console.log("Open");
});
this.webSocket.onClose(function() {
console.log("Cerrando");
}); `
Hi,
thanks for your job, please it's possible to update the package for angular 2 rc.1 ?
Best regards
Cyb
Thank you for providing this WebSocket wrapper for A2!
Why do you return a Promise from send() though? Since you already return something, it might as well be an Observable just to be consistent with the Angular 2 approach.
When in A2 speak A2 :)
Hi,
Is angular2-websocket avalaible with Angular2 RC 1 with npm ?
When i try to install 0.6.3 version (that should be compatible with Angular2 RC 1) , NPM try to install 0.6.2.
Did i do something wrong ?
Sincerely,
Hi there, thank you for the great work on this library firstly.
I am using the same code with the examples, it turns out that with getDataStream, I could get data from server side, but with onMessage I couldn't;
I tested the server side with web-socket test tool and it works.
I create a $websocket instance with the reconnect param: {"reconnectIfNotNormalClose": true}
and the stream nicely reconnects on failures.
I have a problem with incoming messages:
ws.getDataStream().subscribe
correctly fires on incoming messages until the websocket reconnects, after which it stops firing.
Am I missing a step so ws.getDataStream().subscribe
continues firing after an automatic reconnection?
here is the code (comments welcome, I am new to js):
this.ws = new $WebSocket('wss://...', null, JSON.parse('{"reconnectIfNotNormalClose": true}'));
this.ws.getDataStream().subscribe(
(msg: MessageEvent) => console.log('message received: ', msg),
(err) => console.log('incoming websocket err', err),
() => console.log('incoming websocket complete')
);
I also tried moving the subscribe
into the stream's onOpen
, but it behaves the same as above (fires only for the initial connection):
this.ws = new $WebSocket('wss://...', null, JSON.parse('{"reconnectIfNotNormalClose": true}'));
this.stream.onOpen(
this.ws.getDataStream().subscribe(
(msg: MessageEvent) => console.log('message received: ', msg),
(err) => console.log('incoming websocket err', err),
() => console.log('incoming websocket complete')
)
);
Hi, 2 part question:
What would be the best way to initialize the websocket service on initialization of the app? Like, how can you bootstrap the service with angular 2.1.0 in the app module?
Other question is...
Everything is working fine except with capturing the first message with getDataStream()
method/observable. Not sure if it's related to the above question (and my backend is sending messages properly), but yeah, the first message my client app captures is always undefined
, so the messages I capture from the datastream are one event behind.
Ex. (mirror app example)
Client Sends => {1, 2, 3, 4}
client getDataStream Receives => {undefined, 1, 2, 3}
Hi guys, just posting here for visibility.
Just updated angular2 to 2.4.4 and this module to 0.9.0, and noticed that I am having issues in displaying the data.
Not sure if there's an issue with the change detection with angular itself or if it's something with this package. I can see console is receiving the data fine, but was wondering anyone else having issues with websockets and ng2?
In my particular instance, I am having issues displaying data in the view using *ngFor when I receive packets from my websocket.
Is it possible to use this dependency in Angular 4 application?
It will be very helpful me to upgrade my application to Angular 4 from Angular 2..
Hi,
Can you please add usage example ...
I tried to use:
let websocket = new $WebSocket("…");
let observable: Observable = this.websocket.send("test");
observable.subscribe(
value=>console.log("nextValue: " + value),
err=>console.log("error: " + err),
()=>console.log("done.")
);
message arrives to backend, it's returned (to other client), but nothing is logged in console here. Same for using subject.
By using following instead of that:
this.websocket = new $WebSocket("ws://localhost:8280/gerrit-helper/test-websocket-endpoint");
this.websocket.onMessage(function (e) { console.log(e); }, null);
let observable: Observable = this.websocket.send("test");
and subscription to cold observable...
this 'works', but seems really wrong. Why does subscription in first excerpt does not work? (when using Observable.range to verify it seems to work as expected).
Thanks.
With the code on GitHub updated to be fully compliant with RC 4, can you please push a new version to npm?
Recently Angular2 removed their dependency on the es6-shim module so that core-js could be used in it's place. The es6-shim module has licensing issues which prevent it from being commercially distributed. Would it be possible to change your dependency to be on the core-js shim library instead of es6-shim?
RECEIVE WORKS BUT SEND DOESN'T.
I've wrapped message object into the array, because callback function had been called without any arguments and there was no access to 'arguments' array of callback.
onMessageHandler(message: MessageEvent) {
var pattern;
var self = this;
var currentCallback;
for (var i = 0; i < self.onMessageCallbacks.length; i++) {
currentCallback = self.onMessageCallbacks[i];
currentCallback.fn.apply(self, [message]);
}
};
Please can you add this module to Typings ?
How can I use this module on Angular 2 if I use Typings ? I got an error "angular2-websocket not found"
Thanks
Please add a working minimum implementation (demo) to the documentation, as a plunker.
I know this is not a issue but I don't know how I can ask you something.
We are using your websocket in an ionic2 project and it's working great.
There are three things we like to do.
this is how we implemented it for regular http requests
We configure a proxy in our ionic configuration for /api which is working only in dev mode so all HTTP requests where redirected and there is no CORS problem, we found no solution to proxy also Websockt requests. Do you have an idea=
We created a CustomHTTP Interceptor which is used instead of the regular HTTP, this checks if environment is dev or production, if dev we leave the url as it is, in dev mode means /api/ which will be redirect by proxy configuration, if we are in production I change the url to https.... or an other url, it depend if we are on a device or on a browser.
With this interceptor also we can handle http errors and log them.
So we need to do the same thing with your websocket implementation. Did you do something like that before? do you have some examples or some ideas to share with us? We can also open an stack-overflow to discuss this.!
thx for you help
Hi there, I hope someone could tell me when I should use onMessage and/or getDataStream?
I finally got around to upgrading my version to 0.9.0 in my project but it broke everything.
Upon first connect I get a
Error during WebSocket handshake: Invalid status line
According to my logs, the websocket response is a status code of 200 and not 101. If reconnectIfNotNormalClose: true,
I see another websocket request go out (code 101), but this never gets a response back from my server, not even an error code.
Relevant code:
private connectWebSocket() { this.wsocket = new $WebSocket("wss://" + location.hostname + "/wss/whSocket"); this.wsocket.onMessage(this.processData, {}); this.wsocket.onError(this.socketError); }
onMessage()
is never called
I'm getting the below error with the latest angular 2 & ionic beta libraries ...
node_modules\angular2-websocket\angular2-websocket.ts:1
import {Injectable} from "angular2/core";
^
ParseError: 'import' and 'export' may appear only with 'sourceType: module'
Kindly guide
It is not clear yet whether I need to deal with onError and onClose events in my code or it has been done in the library.
The document in the README file is all about sending and receiving messages, my concern is that if any connection issue happened, what I need to do with this library?
First of all, thanks for writing this!
I have run into an issue and I don't know what would be a nice solution. Briefly: when a websocket connection fails, both onClose and onError are called, which makes sense, except for the dataStream
subject.
Consider this snippet:
var x = new Subject();
x.error("error message");
// x.isCompleted === true, therefore:
x.complete(); // raises an ObjectUnsubscribedError
This is exactly what happens when an error occurs. I don't know what would be a nice solution for this, especially if you consider that you (sort of) want to abstract away reconnects in the dataStream (or at least that would be nice from my point of view).
Currently you would need to create another Subject for a new connection, and get the clients to resubscribe. This is OK but might need a bit of refactoring to make this obvious. Example: give the Subject as a parameter to the onInit
callback, so it clearly represents only one connection.
Now I'm just using a stripped down version that does not have that Subject, and use only the callbacks and have my own observables that also perform some application logic.
I'm happy to make a PR after we discuss what would be a nice solution.
All the best,
Vlad
Hi guys, im not a fluent js developer, so this is new for me. im trying to add your library in to a little project, but im getting this error in the browers console:
angular2-websocket.js:11Uncaught ReferenceError: require is not defined
im loading this libraries for angular2:
`
<script type="text/javascript" src="node_modules/core-js/client/shim.min.js"></script><script type="text/javascript" src="node_modules/zone.js/dist/zone.js"></script>
<script type="text/javascript" src="node_modules/reflect-metadata/Reflect.js"></script>
<script type="text/javascript" src="node_modules/rxjs/bundles/Rx.umd.js"></script>
<script type="text/javascript" src="node_modules/@angular/core/bundles/core.umd.js"></script>
<script type="text/javascript" src="node_modules/@angular/common/bundles/common.umd.js"></script>
<script type="text/javascript" src="node_modules/@angular/compiler/bundles/compiler.umd.js"></script>
<script type="text/javascript" src="node_modules/@angular/platform-browser/bundles/platform-browser.umd.js"></script>
<script type="text/javascript" src="node_modules/@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js"></script>
<!-- librerias usadas -->
<script type="text/javascript" src="media/js/angular2-websocket.js"></script>`
Tx for this component. We're starting to use it.
Unfortunately at this version it made our build unstable. The dependency in packag.json on "angular2": "^2.0.0-beta.0" made our application upgrade without any change on our side to angular-beta.05 which broke our build.
Please depend on fixed versions in releases. 😄
There seems to be a breaking change in how send
is implemented. It now returns an cold Observable
, created using Observable.create
which requires a subscribe
in order to fire.
I believe your ultimate goal is to link the observable to the actual successful/failure of the websocket send. However, currently as it stands, it doesn't do that.
However, this change has introduced a new hassle: every call to send
now needs a subscription in order to work.
For example:
Previous: wsock.send(someObj);
Now: wsock.send(someObj).subscribe();
Would you consider creating a hot observable instead? It is not a great idea since hot observables h ave their own overheads.
The best solution might be to have two different send
methods? That is because maybe not many people will care whether the message is successfully sent or not.
this project will support IPv6?
Would be useful to be able to remove listeners after they've been added. For instance, I have a use case where, depending on some UI state, I may or may not want an onMessage
listener. I can handle this currently by setting a flag in the onMessage
callback in order to ignore the message, but would be nice to be able to remove it altogether.
I'm using your lib in version 0.9.1 and have an issue which I didn't seen before.
On opening a simple websocket connection like this
this.ws = new $WebSocket(this.httpService.getFullUrl('/wsapi/v1/sensorsws'));
this.ws.connect();
this.ws.onOpen(function() { that.webSocketOpen(); });
this.ws.onMessage(function(evt) { that.webSocketMessage(evt); });
this.ws.onClose(function(evt) { that.webSocketClose(evt); });
the client opens always to connection on server and on the client the onOpen listener is called also twice times!
I think this behavior wasn't the version I used before.
Hi afrad,
Using lib with ionic 2 app (tested with ionic serve
). When I call close
method websocket doesn't recognize this as 'clean' close. onCloseHandler
handler receives an event with code
== 1005. So the lib is trying to reconnect.
If it's a feature, not a bug, then how can I close the socket without auto reconnect? (I do need auto reconnect if connection is dropped by network issues, etc)
Thank you.
From http://angularjs.blogspot.ru/2016/09/angular-2-rc6_1.html
If you’ve previously deep imported from @angular packages (e.g. @angular/core/src/foo/bar), note that this no longer works in RC6. Always import from the root of a package (eg, @angular/core). Deep imports are private APIs, and likely to change.
Right now angular2-websocket
is starting with errors.
From angular2-websocket.ts
...
import {isPresent, isString, isArray,isFunction} from '@angular/compiler/src/facade/lang';
...
Stacktrace from browser
(index):43 Error: (SystemJS) Unexpected token <
SyntaxError: Unexpected token <
at Object.eval (http://localhost:5005/vendor/angular2-websocket/angular2-websocket.js:13:14)
at eval (http://localhost:5005/vendor/angular2-websocket/angular2-websocket.js:213:4)
at eval (http://localhost:5005/vendor/angular2-websocket/angular2-websocket.js:214:3)
Evaluating http://localhost:5005/vendor/@angular/compiler/bundles/compiler.umd.js/src/facade/lang
Evaluating http://localhost:5005/vendor/angular2-websocket/angular2-websocket.js
...
I've just updated angular2 from RC-3 to RC-5 and I can't get past this error in my console
Error: @http://localhost:3000/node_modules/angular2-websocket/angular2-websocket.js:12:5
@http://localhost:3000/node_modules/angular2-websocket/angular2-websocket.js:1:2
Zone</ZoneDelegate</ZoneDelegate.prototype.invoke@http://localhost:3000/node_modules/zone.js/dist/zone.js:323:20
Zone</Zone</Zone.prototype.run@http://localhost:3000/node_modules/zone.js/dist/zone.js:216:25
scheduleResolveOrReject/<@http://localhost:3000/node_modules/zone.js/dist/zone.js:571:53
Zone</ZoneDelegate</ZoneDelegate.prototype.invokeTask@http://localhost:3000/node_modules/zone.js/dist/zone.js:356:24
Zone</Zone</Zone.prototype.runTask@http://localhost:3000/node_modules/zone.js/dist/zone.js:256:29
drainMicroTaskQueue@http://localhost:3000/node_modules/zone.js/dist/zone.js:474:26
ZoneTask/this.invoke@http://localhost:3000/node_modules/zone.js/dist/zone.js:426:22
Evaluating http://localhost:3000/node_modules/angular2-websocket/angular2-websocket.js
Error loading http://localhost:3000/node_modules/angular2-websocket/angular2-websocket.js as "angular2-websocket/angular2-websocket" from http://localhost:3000
It seems to be triggered by this line in angular2-websocket.js:
var core_1 = require('@angular/core');
systemJS config issue, or other?
I also see that angular2-websocket has this dependency: "@angular/core": "2.0.0-rc.4"
... not sure if that could be a contributing factor..
Please and thank you!
Please update the dependencies to the newest Angular Version.
Hi,
I have this strange issue where I have a ws.getDataStream()
close to the root component, and a subscriber attached to that service via seperate component. But it's causing this weird issue where where it'll receive multiple responses from server, even though it's sending one response.
For example, angular2 client sends request. Server send backs a response fine, and client that recieves that response fine. But if i send another request (like, the same in this scenerio), it'll double the recieved response. Send a third one, and now there's three values that the subscriber is catching.
So an example of this issue is, client sends 1, 2, 3. server sends 1, 2, 3. client subscriber recieves 1, 22, 333
See the comments for the problem and solution:
close(force: boolean = false) {
if (force || !this.socket.bufferedAmount) {
// in onCloseHandler the event.code will be CLOSE_NO_STATUS = 1005
// a this.reconnect will occur
// this.socket.close();
// below the event.code will be this.normalCloseCode
// this.reconnect will no longer occur here
this.socket.close(this.normalCloseCode);
}
return this;
};
// see the event.code usage below passed when calling this.socket.close method
onCloseHandler(event: CloseEvent) {
this.notifyCloseCallbacks(event);
if ((this.config.reconnectIfNotNormalClose && event.code !== this.normalCloseCode)
|| this.reconnectableStatusCodes.indexOf(event.code) > -1) {
this.reconnect();
} else {
this.sendQueue = [];
this.dataStream.complete();
}
};
Is the exemple up to date ?
My Sublime don't find setSendMode methode ? In addition I didn't find it into angular2-websocket.ts
Issue in if (self.socket.readyState !== self.readyStateConstants.RECONNECT_ABORTED) { return false; } else { self.fireQueue(); return true; }
When the connection is open:
- self.socket.readyState is 1
- self.readyStateConstants.RECONNECT_ABORTED is 4
self.fireQueue(); - never run
I think it should be like if (self.socket.readyState === self.readyStateConstants.RECONNECT_ABORTED)
when send data with default subscribe mode, I got "Socket connection has been closed" error;
but I could confirm the socket was still alive as I could still receive server side data with getDataStream() after got that error;
Also I tested with "Simple Web Socket Tool" and I haven't got issues like above.
My code:
`this.ws.send(JSON.stringify(params)).publish().connect();
console.log('1');
this.ws.send(JSON.stringify(params), WebSocketSendMode.Direct);
this.ws.send(JSON.stringify(params), WebSocketSendMode.Promise).then(
(T) => {
console.log('is send');
},
(T) => {
console.log('not send');
}
);
this.ws.send(JSON.stringify(params)).subscribe(
(msg) => {
console.log('next', msg.data);
},
(msg) => {
console.log('error', msg);
},
() => {
console.log('complete');
}
);`
As you'll see, it doesn't try to load the .js
, but an http://localhost:3001/angular2-websocket/angular2-websocket
which of course doesn't exist. I'm using a default systemjs configuration.
Error: patchProperty/desc.set/wrapFn@http://localhost:3001/node_modules/angular2/bundles/angular2-polyfills.js:830:27
Zone</ZoneDelegate</ZoneDelegate.prototype.invokeTask@http://localhost:3001/node_modules/angular2/bundles/angular2-polyfills.js:423:24
Zone</Zone</Zone.prototype.runTask@http://localhost:3001/node_modules/angular2/bundles/angular2-polyfills.js:320:29
ZoneTask/this.invoke@http://localhost:3001/node_modules/angular2/bundles/angular2-polyfills.js:490:29
Error loading http://localhost:3001/angular2-websocket/angular2-websocket as "angular2-websocket/angular2-websocket" from http://localhost:3001/app/chat/chat-service.js
Using .distinctUntilChanged() on an observer created from getDataStream() seems to have no effect. Is the datastream itself adding to the content of the received message?
Hi, a question, how can I set the websocket path realtive and not absolut.
ws://api/v1.... does not work
Is it possible also the set wss or ws dynamically? It depends from where I came if I came over https or http.
thx
Why is line 67 (// self.onMessageHandler(ev);) commented at tag 0.9.0? This causes onMessage method not to fire when a message is received.
I am trying to implement WebSocketConfig but i am having some errors... Anybody can help me showing me a example?
Thanks.
Hi, I'd like to understand why the package.json lists PeerDependencies? Because I don't see any heavy usage of RxJs, for example, that would be broken in other versions of 5.x, so why the beta is a peer dependency? Wouldn't it be better to move to a regular dependency?
I got these unmet dependencies:
npm WARN [email protected] requires a peer of reflect-metadata@^0.1.8 but none was installed.
npm WARN [email protected] requires a peer of [email protected] but none was installed.
npm WARN [email protected] requires a peer of typescript@^2.1.1 but none was installed.
npm WARN [email protected] requires a peer of zone.js@^0.6.25 but none was installed.
I believe, by what I've read in the source, that at least typescript
and rxjs
would work with the newest version
Can't import angular2-websockets in a imports list inside @NgModule decorator. I think that your library can be very useful, but it looks like it's not well prepared to work with final version of angular. Thanks!
Good Night, I am trying to send a message through the socket, but it occurs:
Socket connection has been closed
My Service:
ws = new $WebSocket("ws://localhost:1337/");
send(msg){
this.ws.send(msg).subscribe(
(msg)=> {
console.log("next", msg.data);
},
(msg)=> {
console.log("error", msg);
},
()=> {
console.log("complete");
}
);
}
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.