I am working with a Laravel backend and Angular 6 as the frontend and I am trying to implement broadcasting using socket.io.
I have npm installed laravel-echo socket.io. Following the tutorial from the laravel docs here I am importing the appropriate libraries and attempting to instantiate a new echo instance. This is what that looks like in my app.module.ts:
import { Echo } from 'laravel-echo';
declare global {
interface Window { io: any; }
interface Window { Echo: any; }
}
window.io = window.io || require('socket.io-client');
window.Echo = window.Echo || new Echo({
broadcaster: 'socket.io',
host: 'http://localhost:6001'
});
When I then try to compile the application I get this error:
Uncaught TypeError: laravel_echo__WEBPACK_IMPORTED_MODULE_32__.Echo is not a constructor
Line 59 referenced is the new Echo... call. Any advice is appreciated, thanks.
To fix this I removed all that I included in the app.module.ts file and included the path to the node module in the scripts array in the angular.json file:
"scripts": [
"node_modules/hammerjs/hammer.min.js",
"node_modules/laravel-echo/dist/echo.js"
],
In the component I was then able to reference the Echo object as such:
// At the top of the file
declare global {
interface Window { io: any; }
interface Window { Echo: any; }
}
declare var Echo: any;
window.io = window.io || require('socket.io-client');
window.Echo = window.Echo || {};
Whenever you want to start listening:
window.Echo = new Echo({
broadcaster: 'socket.io',
host: 'https://host-address.com:6001'
});
window.Echo.channel('channel-name')
.listen('.channelEvent', (data) => {
console.log('From laravel echo: ', data);
});
Hope this saves someone else some time!