Giter Club home page Giter Club logo

ngx-socket-io's People

Contributors

13lazegg avatar 3v3ryb0dy avatar akkaraju-satvik avatar captainfl4me avatar dependabot[bot] avatar felixgenicio avatar fhemery avatar fifoosid avatar geo242 avatar gregonnet avatar helveg avatar heuristical avatar insantoshmahto avatar jdforsythe avatar jonaswre avatar littlegubs avatar rodgc avatar sucotronic avatar tomer953 avatar vit100 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ngx-socket-io's Issues

socket.emit() typings are too restrictive

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.

unable to get server data in ngx-socket-io

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

app.module.ts

import { SocketIoModule, SocketIoConfig } from 'ngx-socket-io';
const config: SocketIoConfig = { url: 'http://af098cb1.ngrok.io', options: {} };
 imports: [
    SocketIoModule.forRoot(config),
}

socket.services.ts

 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);
        });
}

Output:

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.

Error: No provider for WrappedSocket!

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>

Samples

@rodgc Can we have a sample with connection.
At the moment I am troubling with receiving message from the server.

Angular 6 - share function

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.

angular 7 issue

Cannot redeclare block-scoped variable 'ngDevMode'.

update please??

url is not honored

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 πŸ˜•

Is this repository still maintained?

@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

FR: Implement callback in emit as observable

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

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.

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

Angular 10 support

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?

Property 'on' does not exist on type 'void' Ionic v4 Angular 7

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.

manual connect

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

Getting ERR_CONNECTION_REFUSED when using https

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)
});

fromEvent not working

I can send, but can't receive

message.service

  public getIncomingMessages$(): Observable<any> {
    return this.socket.fromEvent('message').pipe(
      map((msg: Message): void => {
        console.log('DATA RECEIVED in getMessages$', msg);
        this._saveIncomingMessage(msg);
      }),
    );
  }

from backend

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.

Is support SSR in angular 7 ?

image

My environment

  • win 10 enterprise
  • node v8.11.3
  • npm 5.6.0

Build SSR file found warning message like this ,but not SSR work normaly .

thank you

ERROR in node_modules/ngx-socket-io/node_modules/rxjs/internal/types.d.ts(81,44): error TS1005: ';' expected.

This error is related with the issue ReactiveX/rxjs#4511

Bug Report

Current Behavior

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

subscribersListener problem

#14 is still an issue

Scenario 1 - two listeners for the same event

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

Scenario 2 - two listeners for different events

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

angular 6 and ngx-socket-io 1.1.0 global error

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

is this still being maintained?

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...

query data is lost only in production mode

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
production
development

reconnect error

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');
 })

SafeSubscriber._next error

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)

Release for Angular 9 support

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';
        | ^

Angular 6: Property 'Ι΅NgModuleInjector' does not exist

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.

How to use .of(namespace)?

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!

Angular 8 - Ivy Support /w ng-packagr

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.

Observable not shared

fromEvent<T>(eventName: string): Observable<T> {
this.subscribersCounter++;
return Observable.create( (observer: any) => {
this.ioSocket.on(eventName, (data: T) => {
observer.next(data);
});
return () => {
if (this.subscribersCounter === 1) {
this.ioSocket.removeListener(eventName);
}
};
}).pipe(
share()
);
}

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.

ERROR TypeError: this.socket.fromEvent(...).map is not a function

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.

Error Maximum call stack size exceeded

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);

ERROR in node_modules/ngx-socket-io/src/socket-io.module.d.ts:8:45 - error NG6005

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 ?

Problems using jest and ngx-socket-io

Solution

The solution for this issue is provided in PR #31.

Problem

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

Reproduction

I created a repository demoing the problem: https://github.com/GregOnNet/ngx-socket-io-jest-issue

Steps

  1. git clone https://github.com/GregOnNet/ngx-socket-io-jest-issue.git
  2. cd ngx-socket-io-jest-issue
  3. npm install
  4. npm test

Workaround

Currently, you need to do the following to get jest to work with ngx-socket-io

  1. Install babel-preset-env
  2. Add babel.config.js
  3. Configure 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

  • Tell babel to transform js files
  • Add ngx-socket-io to 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.

Support for Angular 6

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?

Update package.json to Angular 5

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

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,

Can not receive and send events

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.

Event not work after manual reconnect

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

SocketIoModule.forRoot with factory ?

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

How to test services using a Socket?

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);
  });

Using multiple sockets

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!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.