Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Universal server rendering WebSocket

Are there any examples of Angular Universal with WebSockets?

Serverside rendering does not know wat a WebSocket object is in my case. And if I use socket.io the node server hangs when trying to make a connections.

Some additional information about the problem:

I downloaded angular-universal-starter from github: https://github.com/angular/universal-starter Which works fine out of the box running 'npm install' and 'npm start'

But after i added the following code to AppComponent

   export class AppComponent implements OnInit {
       ngOnInit() {
           let webSocket = new WebSocket("----server url----")
       }
   }

I got the following error in my NodeJs server console:

EXCEPTION: WebSocket is not defined
ORIGINAL STACKTRACE:
ReferenceError: WebSocket is not defined
    at AppComponent.ngOnInit (/Volumes/Development/cacadu/website/universal-starter-master2/dist
/server/index.js:41725:29)
like image 933
Marco Avatar asked Jan 17 '17 15:01

Marco


People also ask

Is WebSocket better than socket IO?

Both WebSocket vs Socket.io are popular choices in the market; let us discuss some of the major Difference Between WebSocket vs Socket.io: It provides the Connection over TCP, while Socket.io is a library to abstract the WebSocket connections. WebSocket doesn't have fallback options, while Socket.io supports fallback.

Does Angular support server side rendering?

To implement server side rendering in your Angular application, you can use the Angular Universal package.

Is socket IO same as WebSocket?

What Socket.IO is​ Socket.IO is a library that enables low-latency, bidirectional and event-based communication between a client and a server. It is built on top of the WebSocket protocol and provides additional guarantees like fallback to HTTP long-polling or automatic reconnection.

Can I use socket IO in Angular?

After creating the Angular app, we need to install the Socket. IO-Client package which will help us communicate between our front-end and our server.


Video Answer


1 Answers

Try only calling the websocket on the Client, for example you can detect whether it's the browser or the server with these imports

import { isPlatformBrowser } from '@angular/common';
import { Inject, PLATFORM_ID } from '@angular/core';

Then use them inside your code, this might be able to fix the problem!

@Component({ ... })
export class AppComponent implements OnInit {

    private isBrowser: boolean = isPlatformBrowser(this.platformId);

    constructor(
       @Inject(PLATFORM_ID) private platformId: Object
    ) {
        if (isBrowser) {
            let webSocket = new WebSocket("----server url----");
        }
    }
}
like image 100
Mark Pieszak - Trilon.io Avatar answered Sep 26 '22 07:09

Mark Pieszak - Trilon.io