joeherold / angular2-sails Goto Github PK
View Code? Open in Web Editor NEWAn angular module for using the sails socket.io api in angular2 (@angular)
License: MIT License
An angular module for using the sails socket.io api in angular2 (@angular)
License: MIT License
Hey I am using https://github.com/preboot/angular2-webpack
Following your setup I get following error in the browser:
Uncaught ReferenceError: io is not defined
at eval (eval at <anonymous> (vendor.js:2491), <anonymous>:7:5)
at Object.<anonymous> (vendor.js:2491)
at __webpack_require__ (polyfills.js:53)
at eval (eval at <anonymous> (vendor.js:3486), <anonymous>:1:77)
at Object.<anonymous> (vendor.js:3486)
at __webpack_require__ (polyfills.js:53)
at eval (eval at <anonymous> (vendor.js:2737), <anonymous>:10:1)
at Object.<anonymous> (vendor.js:2737)
at __webpack_require__ (polyfills.js:53)
at Object.<anonymous> (vendor.js:5449)
at __webpack_require__ (polyfills.js:53)
at webpackJsonpCallback (polyfills.js:24)
at vendor.js:1
Any ideas what might be causing that problem?
It has some issue with Angular-4
package.json:-
"@angular/common": "^4.0.0",
"@angular/compiler": "^4.0.0",
"@angular/core": "^4.0.0",
"@angular/forms": "^4.0.0",
"@angular/http": "^4.0.0",
I followed example.md file but facing error :- Cannot read property 'get' of undefined(this._sailsService).
I would appreciate help.
Thanks
Hi Joe,
I am using systemjs to load the libraries. I had to add an entry for Typescript.js. I downloaded the package with NPM. However Typescript takes ages to load when the app first starts. Is there a better way to do this and is it needed?
var map = {
'app': 'app', // 'dist',
'@angular': 'node_modules/@angular',
'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
'rxjs': 'node_modules/rxjs',
'angular2-sails': 'node_modules/angular2-sails',
'typescript': 'node_modules/typescript/lib/typescript.js',
};
Is there any technical reason why io.sails.connect() isn't wrapped to run outside the angular zone? Just wondering because the other io calls are wrapped, and to get my protractor tests -- for a hybrid AngularJS/Angular app I am currently upgrading -- to successfully run, I need to wrap the sailsService.connect() call to run outside the angular zone. Everything seems to work -- including the tests -- but wanted to make sure I wasn't missing anything.
Thanks for the great module.
Resolves this issue -- angular/angular#11853
when i run npm install --save angular2-sails
npm ERR! node v7.6.0
npm ERR! npm v4.1.2
npm ERR! code ELIFECYCLE
npm ERR! [email protected] postinstall: typings install
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] postinstall script 'typings install'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the angular2-sails package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! typings install
npm ERR! You can get information on how to open an issue for this project with:
npm ERR! npm bugs angular2-sails
npm ERR! Or if that isn't available, you can get their info via:
npm ERR! npm owner ls angular2-sails
npm ERR! There is likely additional logging output above.
npm ERR! Please include the following file with any support request:
npm ERR! C:\Users\Logan\Documents\Coding\SureCheck-SupportTools\npm-debug.log
Hi Joe
Thanks again for a great module; I have a questions on how to correctly use it.
I have a lot of different angular services; e.g: UserService, AdministrationService, etc. They all use the SailsService to call Sails.
Basic scenario:
MyProfileComponent -> UserService.updateEmail() -> SailsService.post()...
My problem is that I need to call SailsService.connect()
inside all of my function in all my services, otherwise I get this "Cannot read property 'get' of undefined". The angular services does not have the ngOnInit()
that might have solved this.
I am a bit of a newbie here, so its highly likely me that is doing something wrong - or not doing something more likely.
How do I avoid calling SailsService.connect()
at the beginning of all function/method in my services. (I have a lot of services and functions). I believe I am (right now) opening a new socket.io connection for every single call to the backend.
Is there a smart singleton pattern that should adopt?
Should all my services extend your SailsService and maybe then I could call the e.g UserService.connect()
in the ngOnInit()
in my MyProfileComponent
?
Hi Joe,
I am trying to get this working with systemjs. Do you have any example of the entry needed to support this?
I have the following entry but I'm not sure its complete or correct.
var map = {
'app': 'app', // 'dist',
'@angular': 'node_modules/@angular',
'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
'angular2-sails': 'node_modules/angular2-sails/lib',
};
Tom
Hi. I don't know if is an issue, but I follow your manual and the "on" trigger doesn't work. All the other methods works perfectly, like get, post, put, ... but on it's necessary for realtime communication.
Have you an example how to use it?
In this link talks about your library is "deprecated". Is it right?
Thanks a lot.
It will be great to have a public method which allows to explicitly unsubscribe an observer that was initially subscribed with the specified eventIdentity
. This will be useful, it cases when you know that they won't be any new events triggered from the subscription, and you will like to dispose unused resources.
The new method may be implemented as follow:
this._sailsService.unsubscribe(<eventIdentity>);
I will be open to contribute integrating this feature!
Thanks!
I notice in the get/post and other API calls that it wraps the callback and sends its result using an rxjs subject. In this scenario the observable is hot so if there is sufficient (asynchronous) delay between returning and the code subscribing that is longer than the time for the request to complete then the data might not be received by the caller (ie. subject.next is called before there are any subscribers). The most likely scenario would be if the data was passed to async pipe, in which case there are a few tasks that may run before the change detection updates the transform pipe and the pipe subscribing. It is hopefully slim given that a web server will take more time than a CPU but still exists.
Given the behavior of those particular calls it may make more sense to use a Promise or defer the socket call until subscribed.
When I run my app I get the following log:
Client has connected to the server!
|> Now connected to http://localhost:1337.
\___/ For help, see: http://bit.ly/2q0QDpf
(using sails.io.js browser SDK @v1.1.12)
Then, after about 8 seconds, I get this:
WebSocket connection to 'ws://localhost:4200/socket.io/?__sails_io_sdk_version=1.1.12&__sails_io_sdk_platform=browser&__sails_io_sdk_language=javascript&EIO=3&transport=websocket' failed: WebSocket is closed before the connection is established.
VM2027:442 ====================================
VM2027:442 The socket was unable to connect.
VM2027:442 The server may be offline, or the
VM2027:442 socket may have failed authorization
VM2027:442 based on its origin or other factors.
VM2027:442 You may want to check the values of
VM2027:442 `sails.config.sockets.beforeConnect`
VM2027:442 and `sails.config.sockets.onlyAllowOrigins`
VM2027:442 in your app.
VM2027:442 More info: https://sailsjs.com/config/sockets
VM2027:442
VM2027:442 Technical details:
VM2027:442 Error: websocket error
at d.onError (eval at webpackJsonp.../../../../script-loader/addScript.js.module.exports (addScript.js:9), <anonymous>:17:17396)
at WebSocket.ws.onerror (eval at webpackJsonp.../../../../script-loader/addScript.js.module.exports (addScript.js:9), <anonymous>:18:1596)
at WebSocket.wrapFn [as __zone_symbol___onerror] (zone.js:1070)
at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:424)
at Zone.webpackJsonp.../../../../zone.js/dist/zone.js.Zone.runTask (zone.js:191)
at ZoneTask.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneTask.invokeTask [as invoke] (zone.js:499)
at invokeTask (zone.js:1349)
at WebSocket.globalZoneAwareCallback (zone.js:1358)
at d.doClose (eval at webpackJsonp.../../../../script-loader/addScript.js.module.exports (addScript.js:9), <anonymous>:18:2334)
at d.close (eval at webpackJsonp.../../../../script-loader/addScript.js.module.exports (addScript.js:9), <anonymous>:17:17711)
Any idea what could have gone wrong?
I simply connect with:
ngOnInit() {
// this.devices = this.deviceService.getDevices();
// or
let opts = {
url: "http://localhost:1337",
transports: ['polling', 'websocket']
}
this._sailsService.connect(opts);
// this.socket();
}
Why don't you return at least the statuscode with the data?
I am having a problem I am not able to figure out.
When submitting a POST to /auth/local using the sails service I am getting an error when handling the response.
My code:
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import { Injectable, Inject } from '@angular/core';
import { Http, Headers, Response } from '@angular/http';
import { SailsService } from "angular2-sails";
@Injectable()
export class AuthenticationService {
private url = '/auth/local';
private explicitHost = 'localhost';
private port = '1338';
constructor(@Inject(SailsService) private _backend : SailsService, private http : Http) { this.init() }
init() {
console.log("AuthenticationService --> init");
this._backend.connect("http://" + this.explicitHost + ":" + this.port);
}
login(username: string, password: string) {
return this._backend.post('/auth/local', { "identifier" : username, "password" : password })
.map((response: Response) => {
console.log("AuthenticationService --> login, success " + response);
console.log(response);
// login successful if there's a jwt token in the response
let user = response.json();
//let user = response;
console.log("AuthenticationService --> login, user " + user);
if (user && user.token) {
// store user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify(user));
}
});
}
logout() {
// remove user from local storage to log user out
localStorage.removeItem('currentUser');
}
}
However the response is an error:
TypeError: response.json is not a function
The login is successful and my response object is an object when I log it to the console:
Object {data: Object, statusCode: 200, response: JWR}
data:Object
response:JWR
statusCode:200
proto:Object
My package.json
{
"name": "frontend",
"version": "0.0.0",
"license": "MIT",
"scripts": {
"ng": "ng",
"start": "ng serve --proxy-config proxy.config.json",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
"private": true,
"dependencies": {
"@angular/common": "^4.0.0",
"@angular/compiler": "^4.0.0",
"@angular/core": "^4.0.0",
"@angular/forms": "^4.0.0",
"@angular/http": "^4.0.0",
"@angular/platform-browser": "^4.0.0",
"@angular/platform-browser-dynamic": "^4.0.0",
"@angular/router": "^4.0.0",
"angular2-sails": "^0.2.8",
"core-js": "^2.4.1",
"rxjs": "^5.1.0",
"socket.io-client": "^1.7.3",
"zone.js": "^0.8.4"
},
"devDependencies": {
"@angular/cli": "1.0.0",
"@angular/compiler-cli": "^4.0.0",
"@types/jasmine": "2.5.38",
"@types/node": "~6.0.60",
"angular-cli": "^1.0.0-beta.28.3",
"codelyzer": "~2.0.0",
"jasmine-core": "~2.5.2",
"jasmine-spec-reporter": "~3.2.0",
"karma": "~1.4.1",
"karma-chrome-launcher": "~2.0.0",
"karma-cli": "~1.0.1",
"karma-coverage-istanbul-reporter": "^0.2.0",
"karma-jasmine": "~1.1.0",
"karma-jasmine-html-reporter": "^0.2.2",
"protractor": "~5.1.0",
"ts-node": "~2.0.0",
"tslint": "~4.5.0",
"typescript": "~2.2.0"
``` }
}
Anyone have any ideas?
When you include sails.io.js on page it automatically creates connection. Then when you import angular2-sails it immediately disconnects that previous connection. Why? What is the best way to instantiate the two?
if (io && io.sails) {
if (io && io.socket && io.socket.isConnected) {
io.socket.disconnect();
}
}
when using:
let opts = {
url: SERVER_URL,
headers: {'Authorization':'JWT '+this.jwtToken},
}
this.sailsService.connect(opts);
i am getting:
EXCEPTION: Error in :0:0 caused by: undefined is not an object (evaluating 'this._serverUrl.length')
when i use:
this.sailsService.connect(SERVER_URL, opts);
the opts are totally ignored.
see sails.service.ts line:93 is commented out
// this._opts = opts || {}
I am getting a
GET http://localhost:1337/angular2-sails 404 (Not Found)
Hi
I am using the angular2-sails sailsService as a backend wrapper for my sails backend, and it has worked great when developing locally using angular-cli. I am not in the process on moving the code onto real servers, and I want to use Nginx to serve the Angular2 app.
So Sails is running on 1338 & Nginx is running on 9080 (testing purposes)
I have created an Nginx proxy config like this:
location /socket.io/ {
proxy_pass http://127.0.0.1:1338/;
proxy_redirect http://127.0.0.1:1338/ /;
proxy_read_timeout 60s;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
# May not need or want to set Host. Should default to the above hostname.
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
When running the application I am seeing both HTTP 200s and 404s from the Socket.io calls in the browser:
I looks like the sailsService (socket.io) is calling first using a HTTP GET, which returns a HTTP CODE 200 and then it does a HTTP POST, which returns a HTTP CODE 404, and then a GET, then POST, etc.
The Nginx access logs shows:
127.0.0.1 - - [07/Jun/2017:20:56:28 +0200] "GET /socket.io/?__sails_io_sdk_version=0.13.5&__sails_io_sdk_platform=browser&__sails_io_sdk_language=javascript&EIO=3&transport=polling&t=Lo3waeP HTTP/1.1" 200 21961 "http://localhost:8090/login?returnUrl=%2F" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36" "-"
127.0.0.1 - - [07/Jun/2017:20:56:29 +0200] "POST /socket.io/?__sails_io_sdk_version=0.13.5&__sails_io_sdk_platform=browser&__sails_io_sdk_language=javascript&EIO=3&transport=polling&t=Lo3wafr HTTP/1.1" 404 0 "http://localhost:8090/login?returnUrl=%2F" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36" "-"
When I am running using angular-cli (ng serve or npm start) everything works fine.
What could be the issue?
Hi Joe,
First of all thank you for your work on this library. It is very helpful to those of us looking to use sails and angular.
I am attempting to setup your library with Sails v1.0 and Ionic 2. I read the section in your readme about having to include the socket.io library along with the 'angular2-sails' library, as this does not include a version of it by default. I am positive I have properly included the socket.io-client library as instructed to me by the Ionic 2 team. Including it in Ionic is similar to including third party libraries with the Angular-CLI. (Ionic is a framework built on top of Angular). They both use webpack to compile the app. Here are the instructions I used to include socket.io-client and angular2.sails into my Ionic app: https://ionicframework.com/docs/resources/third-party-libs/ just for reference.
I have followed these steps, and also followed your readme on the setup in app.module.ts and usage in pages. I am certain I followed the instructions to the tee. I am running out of hope because after following all of these instructions as I still am receiving the "io is not defined" message in the console.
Do you have any more suggestions on what I might be missing? Thanks so much.
Parker
I connected my front end with socket by following,
this._sailsService.post("/socketSettings/socketConnection",data ).subscribe( (data) => { console.log(data); } )
And it connected.Now I want to listen for message.How it can be done ?
I have created a basic angular2 app using the angular-cli and installed angular2-sails and socket.io-client. My sails application is running at localhost 1338.
When running my angular2 app I am getting a 404 error:
GET http://localhost:4200/socket.io/?__sails_io_sdk_version=0.13.5&__sails_io_s…owser&__sails_io_sdk_language=javascript&EIO=3&transport=polling&t=LjIO6bs 404
My backend authentication service is calling the sails service:
import { Injectable } from '@angular/core';
import { Http, Headers, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { SailsService } from './sails.service';
import 'rxjs/add/operator/map'
@Injectable()
export class AuthenticationService {
private url = '/auth/local';
private explicitHost = 'localhost';
private port = '1338';
constructor(private _backend : SailsService) { }
ngOnInit() {
this._backend.connect("http://" + this.explicitHost + ":" + this.port);
}
login(username: string, password: string) {
return this._backend.post('/auth/local', JSON.stringify({ username: username, password: password }))
.map((response: Response) => {
// login successful if there's a jwt token in the response
let user = response.json();
if (user && user.token) {
// store user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify(user));
}
});
}
logout() {
// remove user from local storage to log user out
localStorage.removeItem('currentUser');
}
}
I am not sure if there is a config issue or build issue.
My angular-cli.json looks like this:
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"project": {
"name": "curb-frontend"
},
"apps": [
{
"root": "src",
"outDir": "dist",
"assets": [
"assets",
"favicon.ico"
],
"index": "index.html",
"main": "main.ts",
"polyfills": "polyfills.ts",
"test": "test.ts",
"tsconfig": "tsconfig.app.json",
"testTsconfig": "tsconfig.spec.json",
"prefix": "app",
"styles": [
"styles.css",
"css/styles.css"
],
"scripts": [
"assets/js/vendor/sails.io.js"
],
"environmentSource": "environments/environment.ts",
"environments": {
"dev": "environments/environment.ts",
"prod": "environments/environment.prod.ts"
}
}
],
"e2e": {
"protractor": {
"config": "./protractor.conf.js"
}
},
"lint": [
{
"project": "src/tsconfig.app.json"
},
{
"project": "src/tsconfig.spec.json"
},
{
"project": "e2e/tsconfig.e2e.json"
}
],
"test": {
"karma": {
"config": "./karma.conf.js"
}
},
"defaults": {
"styleExt": "css",
"component": {}
}
}
My packpage.json is:
{
"name": "curb-frontend",
"version": "0.0.0",
"license": "MIT",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
"private": true,
"dependencies": {
"@angular/common": "^4.0.0",
"@angular/compiler": "^4.0.0",
"@angular/core": "^4.0.0",
"@angular/forms": "^4.0.0",
"@angular/http": "^4.0.0",
"@angular/platform-browser": "^4.0.0",
"@angular/platform-browser-dynamic": "^4.0.0",
"@angular/router": "^4.0.0",
"angular2-sails": "^0.2.8",
"core-js": "^2.4.1",
"rxjs": "^5.1.0",
"socket.io-client": "^1.7.3",
"zone.js": "^0.8.4"
},
"devDependencies": {
"@angular/cli": "1.0.0",
"@angular/compiler-cli": "^4.0.0",
"@types/jasmine": "2.5.38",
"@types/node": "~6.0.60",
"codelyzer": "~2.0.0",
"jasmine-core": "~2.5.2",
"jasmine-spec-reporter": "~3.2.0",
"karma": "~1.4.1",
"karma-chrome-launcher": "~2.0.0",
"karma-cli": "~1.0.1",
"karma-jasmine": "~1.1.0",
"karma-jasmine-html-reporter": "^0.2.2",
"karma-coverage-istanbul-reporter": "^0.2.0",
"protractor": "~5.1.0",
"ts-node": "~2.0.0",
"tslint": "~4.5.0",
"typescript": "~2.2.0"
}
}
Anyone know where I am going wrong?
ReferenceError: io is not defined
at Object. (http://localhost:8100/build/main.js:56191:5)
at webpack_require (http://localhost:8100/build/main.js:20:30)
at Object. (http://localhost:8100/build/main.js:100897:77)
at webpack_require (http://localhost:8100/build/main.js:20:30)
at Object. (http://localhost:8100/build/main.js:89023:73)
at webpack_require (http://localhost:8100/build/main.js:20:30)
at Object. (http://localhost:8100/build/main.js:126107:70)
at webpack_require (http://localhost:8100/build/main.js:20:30)
at http://localhost:8100/build/main.js:66:18
at http://localhost:8100/build/main.js:69:10
If you call _sailsService.disconnect() method and then connect again,
on subscription subject stored no longer valid and never fire!
you have to clean this._pubsubSubscriptions property in disconnect method
With the given example I am only able to get data once but by adding a new record it does not load.
Sails project is running on http://localhost:1337 and angular2+ cli project is running on http://localhost:4200
Thanks
i had problem before with << import { SailsService } from 'angular2-sails'; >>
"try to include SailsService in angular app but i get typescript error "
when i open nodemodule/angular2-sails i found only dist folder
but the index.ts has this line << export * from './src/sails.service'; >> but when i try to change
<< export * from './src/sails.service'; >> to this << export * from './dist/sails.service'; >>
error gone and i got new error with "Uncaught ReferenceError: io is not defined"
when i open sails.service.js i found that io is not defined so i don't know where is the problem
var Rx_1 = require("rxjs/Rx");
if (io && io.sails) {
if (io && io.socket && io.socket.isConnected()) {
io.socket.disconnect();
}
}
I followed the instructions for the example with Async Pipe but i get that message when i run the application, i am using Angular 4 and Sails 0.12, also i get these messages while the application is running: GET XHR http://localhost:4200/socket.io/ [HTTP/1.1 404 Not Found 3ms]
Socket is trying to reconnect to Sails...
-|>- (attempt #11)
I'm working on a project and i think it would be nice to use your library but I can't seem to figure out how to upload files. Please I need to know how to upload images via the backendservice
Hey Team,
I am using this service.
and on button click i have call post request with this._sailsService.post and i had successfully applied.
but when i use this._sailsService.on in ngOnInit() then this is not fired in another end.
please help me how can i send data from sails server to client (angular 4) or how can i get the data from sails server to client.
please help me asap to resolve such issue.
I've been trying for hours to disable the autoconnect.
I would like to use the service to connect to a different port, but there's simply no way to do it.
Using angular-cli, there's no way to set the autoConnect attribute.
Hello, I would like to use sails.io.js with angular5, so I used angular2-sails module. I managed to connect angular to sails BUT I didn't manage to retrieve the events from sails.js, for example when a new document is created in database. Is there something to configure sails side ? I used this.sailsService.on("user").subscribe(data => console.log("event on user"))
. The get and post methods are perfectly working. Sails side I put
ioclient: require('socket.io-client')('http://localhost:1337'),
io: require('sails.io.js'),
In config/http.js, instead of
var io = require('sails.io.js')( require('socket.io-client') );
because sails cannot load else
I didn't write anything in config/socket.js
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.