I am connect my angular app to a web socket server, the logs on the server shows the angular app is connected sucesfully however on angular it just reloads infinitely also no components/page is rendered
This is my component
import {Component, OnInit} from '@angular/core';
import {WebsocketService} from "../../service/websocket.service";
@Component({
selector: 'app-video-item',
standalone: true,
imports: [],
templateUrl: './video-item.component.html',
styleUrl: './video-item.component.scss'
})
export class VideoItemComponent{
constructor(private websocketService: WebsocketService) { }
ngOnInit() {
}
}
This is my service
import { Injectable } from '@angular/core';
import {io} from "socket.io-client";
@Injectable({
providedIn: 'root'
})
export class WebsocketService {
socket = io("http://localhost:3000/")
}
How to fix this so my angular app will stop loading once it is connected to the web socket server??
Connect to the websocket server, stop angular from loading, render components
The angular app must have SSR turned on.
So angular when rendering in the server waits for all asychronous tasks to complete before rendering so the websocket code is a listener it does not complete.Hence you are getting this issue.
The solution will be to make the code for websocket run only on the browser using isPlatformBrowser
.
import { Injectable } from '@angular/core';
import {io} from "socket.io-client";
import { isPlatformBrowser } from '@angular/common';
import { Inject, PLATFORM_ID } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class WebsocketService {
private isBrowser = false;
socket:any;
constructor(
@Inject(PLATFORM_ID) private platformId: Object
) {
this.isBrowser = isPlatformBrowser(this.platformId)
if (this.isBrowser) {
this.socket = io("http://localhost:3000/")
}
}
}