Git Product home page Git Product logo

ng2-cable's People

Contributors

cionescu 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

Watchers

 avatar  avatar  avatar  avatar

ng2-cable's Issues

Error when 'ng build -prod'

Hello @viktor-shmigol !

When running 'ng build -prod' command, I got the following error:

ERROR in vendor.ab1b9072dee692e1bb85.bundle.js from UglifyJs
Unexpected token: name (Ng2Cable) [vendor.ab1b9072dee692e1bb85.bundle.js:39196,4]

Have you had this kind of problem? I was searching on the internet and I realized something related to es2015, es2016, etc.

Do you have some ideas?

This is my tsconfig.json:

{
  "compilerOptions": {
    "baseUrl": "",
    "declaration": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": ["es6", "dom"],
    "mapRoot": "./",
    "module": "es6",
    "moduleResolution": "node",
    "outDir": "../dist/out-tsc",
    "sourceMap": true,
    "target": "es5",
    "typeRoots": [
      "../node_modules/@types"
    ]
  }
}

Receiving same message multiple times

I have set providers in app.module:

providers: [Ng2Cable, Broadcaster, ...]

And I use ng2-cable functionality on NavComponent:

constructor(..., private ng2cable: Ng2Cable, private broadcaster: Broadcaster) {
    this.initializeWebSocket();
  }

  private initializeWebSocket(): void {
    this.userService.getWebSocketToken().subscribe(res => {
      this.ng2cable.subscribe(`${environment.webSocketHost}/notification?token=${res.token}`, 'NotificationChannel');
      this.initializeWebSocketListening();
    });
  }

  private initializeWebSocketListening(): void {
    this.broadcaster.on<any>('new_notification').subscribe(
      message => {
        console.log(message);
      }
    );
  }

The problem is: Every time I logout and relogin, I receive duplicated messages even I call this.ng2cable.unsubscribe(); as:

ngOnDestroy() {
    if (this.ng2cable)
      this.ng2cable.unsubscribe();
  }

  logout(): void {
    this.userService.logout().subscribe(
      res => { this.ng2cable.unsubscribe(); this.redirectToLoginPage(); },
      error => { this.redirectToLoginPage(); });
  }

What I think is: Even ng2cable is being unsubscribed, broadcasters creates a new subscription every new login, printing a message in console (in my case) for current and past logins (unless I close the browser).

What do you recommend me, @viktor-shmigol ?

Consuming 2 channels on one connection

I have a question about how the code works, say I have 2 channels, NotificationsChannel and ChatsChannel, then I would go and do:

this.cable.subscribe(url, 'NotificationsChannel');
this.cable.subscribe(url, ChatsChannel');

since every subscribe call does a setCable which in turn calls ActionCable.createConsumer isn't this creating 2 connections to the same cable for the 2 channels?

Sorry if this obvious, but I wanted to make sure since I was thinking it might be possible to have the cable support several channels with the same consumer and have disconnect and unsubscribe(channel) methods.

browser freezes

Browser tab freezes when the subscriber receive too many notifications every millisecond.

Add support for Angular 6 (rxjs 6)

Rxjs has now a new version, and subject is now imported directly from 'rxjs'
Operators, like map, filter, switch map can be imported from 'rxjs/operator'

Problem is: even fixing imports, broadcaster.js fails on 'return this._eventBus.asObservable().filter(...)'

Error is:

this._eventBus.asObservable(...).filter is not a function
    at Broadcaster.push../node_modules/ng2-cable/broadcaster.js.Broadcaster.on

Ionic 3 build Problem

Every thing work fine with Ionic serve but when i try to make build for android in ionic. it shows error and i get a blank application error is Uncaught SyntaxError: Use of const in strict mode.

This occur moment i add plugin the application. And this is error is gone the moment i remove this plugin from my application.
Can you please look into this problem

node version 8.0.0
npm version 5.0.0

Broadcast from client to server

I see that you have a method called .broadcast('event', object). I thought it was used for broadcast data from client to server. But seemly not. It's just send to client itself.
So can you explain what does that method truly do?
And how can i broadcast data from client to server?
Thank you in advance

Send parameter when subscribe to channel

To subscribe to a channel, there is this example:
this.ng2cable.subscribe('http://example.com/cable', 'ChatChannel');

but, what if is needed to send a parameter to the channel?
In the Rails docs, it is possible with:

App.cable.subscriptions.create { channel: "ChatChannel", room: "Best Room" }

Different subscribers receiving message from other stream

My app has an component that can be present multiple times at the same time.
On the ngOnInit it subscribes to a channel with a certain id:

this.ng2cable.subscribe('ws://localhost:3000/cable', { channel: 'FeaturesChannel', id: this.feature_id });
I have put some console.log with this.feature_id to be certain that it is different.

The component also 'listens' to what is being broadcasted

this.broadcaster.on('UpdateViewType').subscribe( (message:any) => {
	console.log('updated')
})

My channel subscription is:

class FeaturesChannel < ApplicationCable::Channel
  def subscribed
    stream_from "feature_#{params[:id]}"
  end
end

in some controller from my Rails app, there is:
ActionCable.server.broadcast "feature_" + @feature.id.to_s, { feature: @feature, action: 'UpdateRecommendation' }

só, as far as I understand, the ActionCable should broadcast "feature_{some id}" only to the streams "feature_{some id}", but everyone from this.broadcaster.on('UpdateViewType') is receiving it. If the component have been inserted 3 times, console.log('updated') will appear 3 times.

Is there a bug? Something I'm doing wrong?

ActionCable Consumer

I'm still trying to learn actioncable, but isn't creating a new consumer for every subscription a little excessive? New subscriptions should be using the same consumer.

Cannot read property 'subscriptions' of undefined

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'subscriptions' of undefined
TypeError: Cannot read property 'subscriptions' of undefined

Sometimes ng2Cable is set but its property 'cable' not. In this case, above error is shown.

Can't resolve 'actioncable'

Hi!
I'm trying to include Ng2Cable to my Angular2 application using angular-cli, and receive this error:

ERROR in ./~/ng2-cable/js/ng2-cable.js
Module not found: Error: Can't resolve 'actioncable' in '/home/cesar/perso/mike-angular/node_modules/ng2-cable/js'

In my app.module.ts:

import { Ng2Cable, Broadcaster } from 'ng2-cable/js/index';

@NgModule({
  ...
  providers: [
    ...
    Ng2Cable,
    Broadcaster
  ]
})

Has anyone faced this problem before?
Thanks.

Broadcast method being instantiated twice when leaving a component and coming back again

So when i enter a component that has a this.broadcaster method, leave and come back again, this.broadcaster is called twice. So whenever I receive a broadcast from the rails side, both the this.broadcaster methods from the ionic side will pick it up and will do whatever is inside twice! If I leave the 3rd time and come back, this.broadcaster is called thrice. This is a very serious bug that needs to be addressed asap.

Can't resolve ng2-cable

I have installed the packages as prescribed.
After I include it in my app.component.ts, it breaks, here is the error

ERROR in ./src/app/app.component.ts Module not found: Error: Can't resolve 'ng2-cable' in '/Users/valindogodinho/Projects/ANGULARTCP/src/app' @ ./src/app/app.component.ts 11:0-50 @ ./src/app/index.ts @ ./src/main.ts @ multi main

help please.

How to make rails action cable work with angular 2/4/6/8? Is the subscriber supposed to loop/ping? I'm losing authentication

I am trying to configure my action cable in rails with angular 2+ .

So I used the ng2cable to subscribe to the backend as follows:

Angular component Code

  this.ng2cable.subscribe(
    'ws://localhost:3000/cable?access-token=' +localStorage.getItem("accessToken")+ '&client=' + localStorage.getItem("client")+'&uid='+localStorage.getItem("uid"), 
    'NotificationChannel', 
    {}
  );
  this.broadcaster.on<string>('NotificationChannel').subscribe(
    message => {
      console.log(message);
    }
  );

My Rails connection.rb file

  module ApplicationCable
    class Connection < ActionCable::Connection::Base
    identified_by :current_user

    def connect
      self.current_user = find_verified_user
      logger.add_tags 'ActionCable', current_user.get_email
    end
  private
      def find_verified_user
        access_token = request.query_parameters[:'access-token']
        client_id = request.query_parameters[:client]
        uid=  request.query_parameters[:uid]
        verified_user = User.find_by(email: uid)

        if verified_user && verified_user.valid_token?(access_token, client_id)
          verified_user
        else
          reject_unauthorized_connection
        end
      end
    end
  end

notification_channel.rb

  class NotificationChannel < ApplicationCable::Channel
    def subscribed
      stream_from "notification_channel"
    end
    def unsubscribed
    end
  end

Somewhere in my rails app controller:

ActionCable.server.broadcast "notification_channel", notification: 'this is a notification'

I see that the subscription works fine initially with the fresh tokens as the user is valid. But then, I see that on the server, the following code goes into a loop and tries to validate the tokens sent every few seconds as a part of the subscription. I thought websocket authentication was a one time thing and once the connection was established it would stream continuously.

Output (loops continuosly requiring validation everytime)

  Started GET "/cable?access-token=TJxxxxxxxxxxxxxxxxxxxsg&client=rkxxxxxxxxxxxxxxxxxxa5g&[email protected]" for ::1 at 2019-10-21 18:09:26 +0530
  Remote IP: ::1
  Started GET "/cable/?access-token=TJxxxxxxxxxxxxxxxxxxxsg&client=rkxxxxxxxxxxxxxxxxxxa5g&[email protected]" [WebSocket] for ::1 at 2019-10-21 18:09:26 +0530
  Successfully upgraded to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: Upgrade, HTTP_UPGRADE: websocket)
  An unauthorized connection attempt was rejected
  Failed to upgrade to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: Upgrade, HTTP_UPGRADE: websocket)
  Finished "/cable/?access-token=TJxxxxxxxxxxxxxxxxxxxsg-x_sg&client=rkPOGSNnVt97dUJ1hSDa5g&[email protected]" [WebSocket] for ::1 at 2019-10-21 18:09:27 +0530
  Finished "/cable/?access-token=TJxxxxxxxxxxxxxxxxxxxsg-x_sg&client=rkxxxxxxxxxxxxxxxxxxa5g&[email protected]" [WebSocket] for ::1 at 2019-10-21 18:09:27 +0530

Questions

  1. Is it normal that the subscribe action from the front end ends up pinging the server with the same request every few seconds (Started GET "/cable?access-token=TJxxxxxxxxxxxxxxxxxxxsg&client=rkxxxxxxxxxxxxxxxxxxa5g&uid=[email protected]")? I thought it would just have to authenticate for the first time and then the backend would push information through the web socket.
  2. Clearly , the "An unauthorized connection attempt was rejected" is happening since the token eventually gets outdated with repeated pinging of the same request from the subscriber. If this is an expected result, should I be refreshing the token with every ping? this seems to partially defeat the purpose of using a stream service? Please clarify my understanding.
  3. If this is the expected outcome, how do I send a new token every time as a part of the subscription?

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.