viktor-shmigol / ng2-cable Goto Github PK
View Code? Open in Web Editor NEWConnect your Angular(2/4)/ionic(2/3) application with Rails ActionCable
Home Page: https://ng2-cable-example.herokuapp.com
Connect your Angular(2/4)/ionic(2/3) application with Rails ActionCable
Home Page: https://ng2-cable-example.herokuapp.com
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"
]
}
}
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 ?
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.
WebSocket connection to 'ws://ec2-198.168.16.5.eu-west-2.compute.amazonaws.com/cable' failed: Error during WebSocket handshake: 'Connection' header is missing
Browser tab freezes when the subscriber receive too many notifications every millisecond.
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
I am trying to use ng2-cable with a Rails application. I have the following error when installing it:
npm install ng2-cable --save
[email protected] /Users/luis/Sites/ionic3/eventos
├── UNMET PEER DEPENDENCY @angular/[email protected]
├── [email protected]
└── UNMET PEER DEPENDENCY [email protected]
Maybe it's silly but I'm a rookie in Angular.
My package.json:
Thanks and sorry for my english.
When I ran 'npm install', the following error was shown:
UNMET PEER DEPENDENCY @angular/[email protected]
And this is generating new issues.
I can't seem to get this to install, it throws UNMET PEER DEPENDENCY errors when I run npm install.
I've tried it with Angular 4.0.2, 4.0.3 and 4.1.0.
├── UNMET PEER DEPENDENCY @angular/[email protected]
├── UNMET PEER DEPENDENCY @angular/[email protected]
├── UNMET PEER DEPENDENCY @angular/[email protected]
├── UNMET PEER DEPENDENCY @angular/[email protected]
└─┬ [email protected]
└── [email protected]
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
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
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" }
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?
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.
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.
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.
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.
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.
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
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.