Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
700 views
in Technique[技术] by (71.8m points)

node.js - 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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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----");
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...