rodgc / ngx-socket-io Goto Github PK
View Code? Open in Web Editor NEWSocket.IO module for Angular
License: MIT License
Socket.IO module for Angular
License: MIT License
According to Socket IO's official documentation, client-side socket.emit()
accepts any number of arguments, where the first is a string
and the last may be a Function
. Currently, the type definitions for the socket.emit()
method accepts only a single argument of any
type between the event name and callback function.
For our application, we need to be able to pass multiple data arguments with socket.emit
, and so are using a fork of this with the necessary changes. We'd like to see those changes in this repository, though.
Hi,
I wood like to request you to please help to solve this problem.
i am using ngx-socket-io repository , angular 6. i am connect to the server but i am unable to get the data from the server.
my code is
import { SocketIoModule, SocketIoConfig } from 'ngx-socket-io';
const config: SocketIoConfig = { url: 'http://af098cb1.ngrok.io', options: {} };
imports: [
SocketIoModule.forRoot(config),
}
constructor(private socket: Socket) {
}
getMessage() {
return this.socket
.fromEvent<any>("sendchat")
.map(data => data.msg);
}
getData(){
console.log("-----------");
this.socket.on('sendchat', function (socket) {
console.log('User data', socket);
});
}
it prints this ----------------------
but can not get the user data and response.and also i not get the single error message i cont understand whats going on please help out.
i've gotten an error don't know where it comes from, if you need to know something about my code for the fix just ask!
thanks in advance
ERROR Error: Uncaught (in promise): Error: No provider for WrappedSocket!
Error: No provider for WrappedSocket!
at injectionError (core.es5.js:1169)
at noProviderError (core.es5.js:1207)
at ReflectiveInjector_.webpackJsonp.../../../core/@angular/core.es5.js.ReflectiveInjector_._throwOrNull (core.es5.js:2649)
at ReflectiveInjector_.webpackJsonp.../../../core/@angular/core.es5.js.ReflectiveInjector_._getByKeyDefault (core.es5.js:2688)
at ReflectiveInjector_.webpackJsonp.../../../core/@angular/core.es5.js.ReflectiveInjector_._getByKey (core.es5.js:2620)
at ReflectiveInjector_.webpackJsonp.../../../core/@angular/core.es5.js.ReflectiveInjector_.get (core.es5.js:2489)
at resolveNgModuleDep (core.es5.js:9562)
at NgModuleRef_.webpackJsonp.../../../core/@angular/core.es5.js.NgModuleRef_.get (core.es5.js:10644)
at resolveDep (core.es5.js:11147)
at createClass (core.es5.js:11003)
at injectionError (core.es5.js:1169)
at noProviderError (core.es5.js:1207)
at ReflectiveInjector_.webpackJsonp.../../../core/@angular/core.es5.js.ReflectiveInjector_._throwOrNull (core.es5.js:2649)
at ReflectiveInjector_.webpackJsonp.../../../core/@angular/core.es5.js.ReflectiveInjector_._getByKeyDefault (core.es5.js:2688)
at ReflectiveInjector_.webpackJsonp.../../../core/@angular/core.es5.js.ReflectiveInjector_._getByKey (core.es5.js:2620)
at ReflectiveInjector_.webpackJsonp.../../../core/@angular/core.es5.js.ReflectiveInjector_.get (core.es5.js:2489)
at resolveNgModuleDep (core.es5.js:9562)
at NgModuleRef_.webpackJsonp.../../../core/@angular/core.es5.js.NgModuleRef_.get (core.es5.js:10644)
at resolveDep (core.es5.js:11147)
at createClass (core.es5.js:11003)
at resolvePromise (zone.js:770)
at resolvePromise (zone.js:741)
at zone.js:818
at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:424)
at Object.onInvokeTask (core.es5.js:3924)
at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423)
at Zone.webpackJsonp.../../../../zone.js/dist/zone.js.Zone.runTask (zone.js:191)
at drainMicroTaskQueue (zone.js:584)
at <anonymous>
@rodgc Can we have a sample with connection.
At the moment I am troubling with receiving message from the server.
Im using "ngx-socket-io": "^1.1.0" and "rxjs-compat": "^6.2.1" at run my app have this issue:
ERROR TypeError: rxjs__WEBPACK_IMPORTED_MODULE_1__.Observable.create(...).share is not a function at WrappedSocket.push../node_modules/ngx-socket-io/src/socket-io.service.js.WrappedSocket.fromEvent
Thanks.
Cannot redeclare block-scoped variable 'ngDevMode'.
update please??
Creating a simple socket does not honor the url:
export class LogSocket extends Socket {
constructor(url: string){
super({url: url, options: {})
}
}
...
const socket = new LogSocket("http://localhost/api/logs")
In the logs I can see that the call is made to http://localhost/socket.io/?EIO=3&transport=poll
π
@rodgc Would be important for us to know if it makes sense to utilize this repo in the future? I think merging some of the PRs would be a great first step to make this project alive again :)
Regards from Germany
WebSocket is already in CLOSING or CLOSED state.
It would be nice if i could subscribe to acknowledgement from backend in angular way.
For example
this.socket.emit('user:fetch').subscribe(data => console.log(data)) // Outputs user info from backend
command: sudo ionic build platform android --debug --verbose --prod --base-href=rro2store/
ERROR in ngx-socket-io/ngx-socket-io.ts(10,40): Error during template compile of 'Ι΅b'
Function calls are not supported in decorators but 'InjectionToken' was called.
ngx-socket-io/ngx-socket-io.ts(10,40): Error during template compile of 'Ι΅b'
Function calls are not supported in decorators but 'InjectionToken' was called.
ngx-socket-io/ngx-socket-io.ts(10,40): Error during template compile of 'Ι΅b'
Function calls are not supported in decorators but 'InjectionToken' was called.
: Can't resolve all parameters for Ι΅a in /home/joslan/Documents/rro2store/node_modules/ngx-socket-io/ngx-socket-io.d.ts: (?).
: Unexpected value '[object Object]' imported by the module 'AppModule in /home/joslan/Documents/rro2store/rro2store/src/app/app.module.ts'. Please add a @NgModule annotation.
βββ¬ @angular-devkit/[email protected] β βββ @angular-devkit/[email protected] deduped βββ¬ @angular-devkit/build-angular@0.801.3 β βββ @angular-devkit/[email protected] deduped β βββ¬ @angular-devkit/[email protected] β βββ¬ @angular-devkit/[email protected] β β βββ @angular-devkit/[email protected] deduped β β βββ @angular-devkit/[email protected] deduped β βββ @angular-devkit/[email protected] deduped β β βββ @angular-devkit/[email protected] deduped βββ¬ @angular-devkit/[email protected] βββ¬ @angular-devkit/[email protected] β βββ @angular-devkit/[email protected] deduped βββ¬ @angular/[email protected] β βββ¬ @angular-devkit/[email protected] β β βββ @angular-devkit/[email protected] deduped β βββ¬ @angular-devkit/[email protected] β βββ¬ @angular-devkit/[email protected] β β βββ @angular-devkit/[email protected] deduped β βββ¬ @schematics/angular@8.3.0 β β βββ @angular-devkit/[email protected] deduped β β βββ @angular-devkit/[email protected] deduped β β βββ¬ @angular-devkit/[email protected] β β βββ¬ @angular-devkit/[email protected] β β β βββ @angular-devkit/[email protected] deduped βββ¬ @angular/[email protected] βββ¬ @angular/[email protected] βββ¬ @angular/[email protected] βββ¬ @angular/[email protected] βββ¬ @angular/[email protected] βββ @angular/[email protected] βββ¬ @angular/[email protected] βββ¬ @angular/[email protected] βββ¬ @angular/[email protected] βββ¬ @ionic/angular@4.8.0 βββ¬ @ionic/angular[email protected] β βββ¬ @schematics/angular@8.1.3 β β βββ @angular-devkit/[email protected] deduped β β βββ @angular-devkit/[email protected] deduped
An Angular 9 app can't be updated to the latest Angular 10 release, since this library does not support it:
Package "ngx-socket-io" has an incompatible peer dependency to "@angular/core" (requires "^8.0.0" (extended), would install "10.0.0").
Package "ngx-socket-io" has an incompatible peer dependency to "@angular/common" (requires "^8.0.0" (extended), would install "10.0.0").
Could you update your package.json file?
Hi I am trying to emit to a namespace but I get the following error: Property 'on' does not exist on type 'void'
I am trying to follow as well what it says on the socketio website but here is the code:
import { Socket } from 'ngx-socket-io';
export class ChatService {
constructor(private socket: Socket){}
public sendMessage(msg: any){
const nsp = this.socket.of(`/${msg.id}`);
nsp.on('connection', socket => { //Property 'on' does not exist on type 'void'
socket.emit('new-message', msg);
})
}
}
is this error happening because Socket returns an observable? How should I be managing various namespaces for different chats a user has?
for some reason I am just having a hard time getting my head around sockets and namespaces vs rooms etc. I am sure I am just being stupid about this but can't seem to find a previously asked question about this. thank you.
Hi,
I have in my app.modules.ts this:
const config: SocketIoConfig = { url: ${environment.host}
, options: {} };
...
imports: [
... SocketIoModule.forRoot(config)
],
My socket.io be connected at bootstrap. Can I connect socket manually ?
Tnx
Hello, I'm having troubles when I deploy the server on https, I always get a net::ERR_CONNECTION_REFUSED, I checked the certificates and seems to be okay. I tried changing the client url on the socket options to localhost, 127.0.0.1, 0.0.0.0 and the domain of the deploy.
Also I put some parameters like " rejectUnauthorized: false" and "secure: true" and I'm no getting any results
The following code is what I have on the back end
'use strict'
const express = require('express'); // const bodyParser = require('body-parser'); // const path = require('path');
const fs = require('fs');
const environmentVars = require('dotenv').config();
// Google Cloud
const speech = require('@google-cloud/speech');
const speechClient = new speech.SpeechClient(); // Creates a client
const app = express();
const port = 1337;
//const server = require('http').createServer(app);
//const io = require('socket.io')(server);
var https = require('https');
var privateKey = fs.readFileSync('/etc/letsencrypt/live/x4-0001/privkey.pem', 'utf8');
var certificate = fs.readFileSync('/etc/letsencrypt/live/x4-0001/cert.pem', 'utf8');
var credentials = {
key: privateKey,
cert: certificate
};
console.log(credentials);
var server = https.createServer(credentials, app);
const io = require('socket.io')(server);
app.use('/assets', express.static(__dirname + '/public'));
app.use('/session/assets', express.static(__dirname + '/public'));
app.set('view engine', 'ejs');
// =========================== ROUTERS================================//
app.get('/', function (req, res) {
res.render('index', {});
});
app.use('/', function (req, res, next) {
next(); // console.log(`Request Url: ${req.url}`);
});
// =========================== SOCKET.IO ================================ //
io.on('connection', function (client) {
console.log('Client Connected to server');
let recognizeStream = null;
client.on('join', function (data) {
client.emit('messages', 'Socket Connected to Server');
});
client.on('messages', function (data) {
client.emit('broad', data);
});
client.on('startGoogleCloudStream', function (data) {
startRecognitionStream(this, data);
});
client.on('endGoogleCloudStream', function (data) {
stopRecognitionStream();
});
client.on('binaryData', function (data) {
// console.log(data); //log binary data
if (recognizeStream !== null) {
recognizeStream.write(data);
}
});
function startRecognitionStream(client, data) {
recognizeStream = speechClient.streamingRecognize(request)
.on('error', console.error)
.on('data', (data) => {
process.stdout.write(
(data.results[0] && data.results[0].alternatives[0])
? `Transcription: ${data.results[0].alternatives[0].transcript}\n`
: `\n\nReached transcription time limit, press Ctrl+C\n`);
client.emit('speechData', data);
// if end of utterance, let's restart stream
// this is a small hack. After 65 seconds of silence, the stream will still throw an error for speech length limit
if (data.results[0] && data.results[0].isFinal) {
stopRecognitionStream();
startRecognitionStream(client);
// console.log('restarted stream serverside');
}
});
}
function stopRecognitionStream() {
if (recognizeStream) {
recognizeStream.end();
}
recognizeStream = null;
}
});
// =========================== START SERVER ================================ //
server.listen(port, "127.0.0.1", function () { //http listen, to make socket work
// app.address = "127.0.0.1";
console.log('Server started on port:' + port)
});
I can send, but can't receive
public getIncomingMessages$(): Observable<any> {
return this.socket.fromEvent('message').pipe(
map((msg: Message): void => {
console.log('DATA RECEIVED in getMessages$', msg);
this._saveIncomingMessage(msg);
}),
);
}
the message is getting sent to testuser with a socket ID of AT97rgogUDPQccO5AAAB
//below is the collection of socketIDs, it is being sent correctly, but not being received
{
marquesperiera98876: 'v25NK5JaJBl-XJchAAAA',
testuser: 'AT97rgogUDPQccO5AAAB'
}
double, triple checking that the socket is being properly emitted to, it is correct, nothing is received.
This error is related with the issue ReactiveX/rxjs#4511
I am getting following errror after using ng build --prod on Amazon CodeBuild
ERROR in node_modules/ngx-socket-io/node_modules/rxjs/internal/types.d.ts(81,44): error TS1005: ';' expected.
node_modules/ngx-socket-io/node_modules/rxjs/internal/types.d.ts(81,74): error TS1005: ';' expected.
node_modules/ngx-socket-io/node_modules/rxjs/internal/types.d.ts(81,77): error TS1109: Expression expected.
Expected behavior
ng build command should run without any error.
Environment
Runtime: Node.js 8.x LTS Carbon and npm
ngx-socket-io version: 2.1.1
RxJS version: 6.4.0
#14 is still an issue
If you call fromEvent()
twice with the same event, the subscribersCounter
goes to 2. If you unsubscribe one of those events, the counter never decrements, so it is still at 2. Now if you unsubscribe the final listener, the counter is still at 2 and the removeListener()
is never called
If you call fromEvent()
twice with different events, the subscribersCounter
goes to 2. If you unsubscribe from either of these events, the counter doesn't decrement - but even if it did, it would still be 1 even though there are no more subscribers for that particular event, because the counter is global and not per-event.
Additionally socket.removeListener()
takes two arguments - not just the event name but also the listener callback, as it's inherited from https://nodejs.org/docs/latest/api/events.html#events_emitter_removelistener_eventname_listener
I'm getting this error into an Angular 7 application. Do i need to include the following line
(window as any).global = window;? Thanks for your help :)
Hi ,
Im getting this error with version 1.1.0
is-buffer.js:4 Uncaught ReferenceError: global is not defined at Object../node_modules/socket.io-parser/is-buffer.js (is-buffer.js:4) at __webpack_require__ (bootstrap:81) at Object../node_modules/socket.io-parser/binary.js (binary.js:8) at __webpack_require__ (bootstrap:81) at Object../node_modules/socket.io-parser/index.js (index.js:8) at __webpack_require__ (bootstrap:81) at Object../node_modules/socket.io-client/lib/index.js (index.js:7) at __webpack_require__ (bootstrap:81) at Object../node_modules/ngx-socket-io/src/socket-io.service.js (vendor.js:115374) at __webpack_require__ (bootstrap:81)
and trying to solve it by putting in the pollyfils the line
(window as any).global = window;
but without results.
Regards
there are some things that I would like to do to improve including some issues but I see here that there are pull requests from 2018...
hi, first thanks for your work :)
i have a angular application integrated with your package, it has the following configuration in root module:
SocketIoModule.forRoot({ url: environment.socket.url, options: { query: { userId: (<any>window).MaxDuel.instance.userId } } })
it works like charm only in development mode :D
as soon as i ng build my app --prod
the user id becomes null
this fires when reconnect but .. when you call this this.socket.emit it will throw
Cannot read property 'emit' of undefined
this.socket.on("reconnect", function (params: any) {
console.log("reconnect")
//this.socket.emit('user_reconnect');
})
ngx-socket-io/src/socket-io.service.ts
Line 61 in 18a219a
If I will listen to 2 or more event then this.subscribersCounter will never be equal to 1
On local environment, but when we move to server with SSL, this issue popup. Is that means that something with SSL should be configured?
ERROR TypeError: Cannot read property '_id' of null
at SafeSubscriber._next (main.js:2199)
at SafeSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.__tryOrUnsub (vendor.js:125723)
at SafeSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.next (vendor.js:125661)
at Subscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._next (vendor.js:125599)
at Subscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (vendor.js:125563)
at MapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/map.js.MapSubscriber._next (vendor.js:133763)
at MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (vendor.js:125563)
at FilterSubscriber.push../node_modules/rxjs/_esm5/internal/operators/filter.js.FilterSubscriber._next (vendor.js:132903)
at FilterSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (vendor.js:125563)
at MergeMapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/mergeMap.js.MergeMapSubscriber.notifyNext (vendor.js:134257)
I would like to use this package with Angular 9.
Last commit e39df3e adds Angular 9 support.
Can we make a new 3.0.2 release?
When trying to source the master branch directly in package.json
"ngx-socket-io": "rodgc/ngx-socket-io#master",
I get an error when running jest test npm run test
β Test suite failed to run
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
Here's what you can do:
β’ To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
β’ If you need a custom transformation specify a "transform" option in your config.
β’ If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html
Details:
/Users/ascandaliato/divergent3d/design-optimization-app/node_modules/ngx-socket-io/index.ts:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){export { SocketIoModule } from './src/socket-io.module';
^^^^^^
SyntaxError: Unexpected token export
1 | import { Injectable } from '@angular/core';
> 2 | import { Socket } from 'ngx-socket-io';
| ^
Hi,
First of all thanks for the plugin, but i'm facing this problem and i'm doing whatever to fix it but cannot get any solution, what i'm doing wrong?
Access to XMLHttpRequest at 'https://server.herokuapp.com/socket.io/?EIO=3&transport=polling&t=Mnn5eIt' from origin 'http://localhost:8100' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Thank you so much
Hello,
I just upgraded to angular 6. All working except ngx-socket-io.
When starting apps it give error:
Property 'map' does not exist on type 'Observable<{}>'
I'm sure map and Observable is properly imported. So i tried to import ngx-socket-io manually to my project. Then it show this error:
ERROR in src/app/shares/ngx-socket-io/socket-io.module.ngfactory.ts(11,46): error TS2339: Property 'Ι΅NgModuleInjector' does not exist on type 'typeof "W:/Webs/myapp/node_modules/@angular/core/core"'.src/app/shares/ngx-socket-io/socket-io.module.ngfactory.ts(27,88): error TS2511: Cannot create an instance of an abstract class.
Hi! i was trying to use .of(namespace) but I could not figure out how to use it.
When I injected Socket in my Angular Service and called .of('myNamespace') on the WrappedSocket instance I got the error:
ERROR TypeError: this.ioSocket.of is not a function at WrappedSocket.push../node_modules/ngx-socket-io/src/socket-io.service.js.WrappedSocket.of (socket-io.service.js:21)
It would be great to have a little documentation / an example about how to use this function.
Thank you!
Issue: not able to compile angular 8-rc.3 projet with ngx-socket-io
ERROR in Value at position 1 in the NgModule.importss of SocketModule is not a reference: [object Object]
resolution? : package lib with ng-packagr in order to generate AOT metadata.
How should we connect with 2 namespaces without creating 2 connection as it is a feature of Socket IO
https://socket.io/docs/rooms-and-namespaces/#Namespaces
ngx-socket-io/src/socket-io.service.ts
Lines 59 to 73 in e39df3e
The share()
operator here doesn't have any effect because a new Observable is returned for every call. The Observable should be persisted for each event type until the last .unsubscribe()
is called.
Although I do
import 'rxjs/add/operator/map'
in my chat.service, It always show the error
ERROR TypeError: this.socket.fromEvent(...).map is not a function
I found that there's no method map
in the Observable at all, and when I add
import 'rxjs/add/operator/map'
to the source code file socket-io.service.js
Everything is ok
Is there somthing wrong with my code or bug in the code ? Please help me. Thanks a lot.
I got this error after some movements between modules. My socket config is in root module,
import { SocketIoModule, SocketIoConfig } from 'ngx-socket-io';
const config: SocketIoConfig = { url: window.location.origin, options: {} };
@NgModule({
declarations: [
...
],
imports: [
...
SocketIoModule.forRoot(config),
...
],
providers: [
...
],
bootstrap: [AppComponent]
})
and the error log
ERROR RangeError: Maximum call stack size exceeded
at Function.[Symbol.hasInstance] (<anonymous>)
at hasBinary (index.js:46)
at hasBinary (index.js:58)
at hasBinary (index.js:58)
at hasBinary (index.js:37)
at hasBinary (index.js:58)
at hasBinary (index.js:58)
at hasBinary (index.js:37)
at hasBinary (index.js:58)
at hasBinary (index.js:58)
which tell generally that we call function inside function. That's error popup when I do simple emit
this.socket.emit("to", obj);
Hello,
I have this error on my console after initial config in app.module on Angular 9.
ERROR in node_modules/ngx-socket-io/src/socket-io.module.d.ts:8:45 - error NG6005: SocketIoModule.forRoot returns a ModuleWithProviders type without a generic type argument. Please add a generic type argument to the ModuleWithProviders type. If this occurrence is in library code you don't control, please contact the library authors.
Any idea ?
Is there any way to set the client to only use websocket as transports ( instead of pooling )?
The solution for this issue is provided in PR #31.
Hi @rodgc,
as mentioned in #31 I experience an error if I run jest next to ngx-socket-io.
The current bundle needs to be transformed with babel to get it to work
I created a repository demoing the problem: https://github.com/GregOnNet/ngx-socket-io-jest-issue
Steps
Currently, you need to do the following to get jest to work with ngx-socket-io
babel-preset-env
babel.config.js
jest.setup.js
1
npm install -D babel-preset-env
2
// babel.config.js
module.exports = function(api) {
api.cache(true);
const presets = ['env'];
const plugins = [];
return {
presets,
plugins
};
};
3
transformIgnorePatterns
(making jest passing the js files to babel)module.exports = {
preset: "jest-preset-angular",
roots: ["src"],
setupFilesAfterEnv: ["<rootDir>/src/setup-jest.ts"],
moduleNameMapper: {
"@app/(.*)": "<rootDir>/src/app/$1",
"@assets/(.*)": "<rootDir>/src/assets/$1",
"@core/(.*)": "<rootDir>/src/app/core/$1",
"@env": "<rootDir>/src/environments/environment",
"@src/(.*)": "<rootDir>/src/src/$1",
"@state/(.*)": "<rootDir>/src/app/state/$1"
},
transform: {
"^.+\\.(ts|html)$":
"<rootDir>/node_modules/jest-preset-angular/preprocessor.js",
"^.+\\.js$": "babel-jest"
},
transformIgnorePatterns: ["node_modules/(?!(jest-test|ngx-socket-io))"]
};
Please let me know if you need further information.
I'm trying Angular 6 with this package and to run the app appear this error:
ERROR in ./node_modules/ngx-socket-io/src/socket-io.service.js
Module not found: Error: Can't resolve 'rxjs/Observable'
Any solution?
I'm using the project in a project and after updating to angular 5, all is working fine. But because de peerDependency is se to angular ^4.1.3 , a warning is shown by npm.
socket disconnect after make mobile browser onpause in android and iphone
---->my setting :
allowUpgrades: false,
upgradeTimeout:60000,
reconnection: false,
pingInterval: 40000,
pingTimeout:60000,
reconnectionDelay: 5000,
I have implemented socket-io
server in my app and I am using ngx-socket-io
for my Angular
application communicating with that server.
My server implementation:
const io = socketio(server);
io.on('connection', socket => {
console.log('connection!')
socket.emit('notification');
});
After connecting to my app, the connection!
message is printed successfully, means the client successfully linked to the WS server.
But my notification
event listener is not receiving any events...
My WebSocketService
:
import { Injectable } from '@angular/core';
import { Socket } from 'ngx-socket-io';
@Injectable()
export class WebSocketService {
constructor(
private socket: Socket,
) {}
public getEventListener() {
return this.socket.fromEvent('notification');
}
}
Subscription (In other service):
@Injectable()
export class NotificationService {
...
constructor(
private wsService: WebSocketService,
) {
console.log('Test')
this.wsService.getEventListener().subscribe(() => console.log(123));
}
...
}
Test
is printed but 123 is not.
Hello,
I have a big issue with my app, i try to find a solution to reconnect my socketio connection manualy. I explain my issue.
I developped an app with a little chat, the frontend with angular7, and the backend with nodejs. When i connect to my app with my login, all works correctly, i received my data from the backend, all of my events works also, its great !
But when i refresh the page, i catch the io server disconnect event on disconnect, and i try to reconnect the socket manualy.
case 'io server disconnect':
this.socket.ioSocket.io.opts.query = {
origin: '*',
reconnect: true,
reconnectionDelay: 1000,
reconnectionDelayMax: 5000,
reconnectionAttempts: Infinity,
autoConnect: true,
forceNew: true,
reconnection: true,
secure: environment.chat.socket.secure
}; // new options
// Add url of the socket
this.socket.ioSocket.io.uri = environment.chat.socket.url + ':' + environment.chat.socket.port;
// Connect the socket
this.socket.connect(); // manually connection
break;
But i received nothing from event, all events are completly disconnected to the socket.
However when i check with console.log the content of my socket, the socket is connected.....
it's been two days since I can not find a solution
Can you help me please ?
Thanks
Regards
Decad7
Hi there i'm using this module like this:
const config: SocketIoConfig = { url: endpoint.socket, options: {
query: {
token: localStorage.getItem('access_token')
}
}};
...
SocketIoModule.forRoot(config),
But i need to use Ionic storage instead of localstorage.
I'm wondering if there is a factory method to use like @auth0/angular-jwt:
export function jwtOptionsFactory(storage: Storage) {
return {
tokenGetter: () => {
return storage.get('access_token');
},
whitelistedDomains: endpoint.jwtWhitelist
}
....
JwtModule.forRoot({
jwtOptionsProvider: {
provide: JWT_OPTIONS,
useFactory: jwtOptionsFactory,
deps: [Storage]
}
}),
}
Regards
I have a service for which I made a couple of HTTP tests. After adding ngx-socket-io
though, they don't work anymore, even though I'm not testing the socket features at all.
Here's the error I get:
NullInjectorError: R3InjectorError(DynamicTestModule)[ResourcesService -> WrappedSocket -> WrappedSocket]:
NullInjectorError: No provider for WrappedSocket!
And here's my testing setup:
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [ResourcesService],
});
injector = getTestBed();
service = injector.inject(ResourcesService);
httpMock = injector.inject(HttpTestingController);
});
Any help would be highly appreciated.
EDIT:
I figured it out. I was missing the same imports from the app.module.ts
.
Therefore, my final setup looks like this:
import { SocketIoModule, SocketIoConfig } from 'ngx-socket-io';
const config: SocketIoConfig = {
url: environment.SOCKET_ENDPOINT,
options: {},
};
...
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule, SocketIoModule.forRoot(config)],
providers: [ResourcesService],
});
injector = getTestBed();
service = injector.inject(ResourcesService);
httpMock = injector.inject(HttpTestingController);
});
i hope solve a problem like this https://stackoverflow.com/questions/4743592/send-additional-data-on-socket-connection
Trying to use two sockets as per instructions gives me errors.
I have added socket in providers array in page module.
providers: [Socket]
In app.module:
import { Socket } from 'ngx-socket-io';
and the two export class SocketOne extends Socket { ...
providers: [
SocketOne, SocketTwo,
This is in an Ionic 4 /Angular 7 app.
This is my error:
ERROR Error: Uncaught (in promise): Error: StaticInjectorError(AppModule)[WrappedSocket -> InjectionToken SOCKET_IO_CONFIG]:
StaticInjectorError(Platform: core)[WrappedSocket -> InjectionToken SOCKET_IO_CONFIG]:
NullInjectorError: No provider for InjectionToken SOCKET_IO_CONFIG!
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.