Angular fails to establish connection due to termination before receiving a handshake response

While attempting a socket connection, an error popped up. I am following this tutorial on tutorialedge.net but using a different endpoint for implementation.

socket.service.ts

import { Injectable } from '@angular/core';
import * as Rx from 'rxjs/Rx';

@Injectable({
providedIn: 'root'
})
export class SocketService {

constructor() { }

private subject: Rx.Subject<MessageEvent>;

public connect(url): Rx.Subject<MessageEvent> {
if (!this.subject) {
  this.subject = this.create(url);
  console.log("Successfully connected: " + url);
  } 
  return this.subject;
  }

  private create(url): Rx.Subject<MessageEvent> {
  let ws = new WebSocket(url);

  let observable = Rx.Observable.create(
  (obs: Rx.Observer<MessageEvent>) => {
    ws.onmessage = obs.next.bind(obs);
    ws.onerror = obs.error.bind(obs);
    ws.onclose = obs.complete.bind(obs);
    return ws.close.bind(ws);
   })
 let observer = {
    next: (data: Object) => {
        if (ws.readyState === WebSocket.OPEN) {
            ws.send(JSON.stringify(data));
        }
    }
}
return Rx.Subject.create(observer, observable);
}
}

chat.service.ts

import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs/Rx';
import {SocketService} from '../services/socket.service';

let ws_scheme = window.location.protocol == "https:" ? "wss" : "ws";
let ws_path = ws_scheme + '://' + window.location.host + 
"/api/chat/stream/";
const CHAT_URL = ws_path;

export interface Message {
author: string,
message: string
}

@Injectable({
providedIn: 'root'
})

export class UploadSocketService {

public messages: Subject<Message>;

constructor(wsService: SocketService) { 
this.messages = <Subject<Message>>wsService
        .connect(CHAT_URL)
        .map((response: MessageEvent): Message => {
            let data = JSON.parse(response.data);
            return {
                author: data.author,
                message: data.message
            }
        });
}
}

An issue arises in the socket.service.ts file at the line where it has let ws = new WebSocket(url);

Any suggestions on resolving this?

Answer №1

In order to route /api/ requests to your backend using the angular cli proxy, it is essential to include ws: true in the proxy configuration. Without this setting, the websocket connection will not be established properly.

{
  "/api/": {
    "target": "http://localhost:8080",
    "secure": false,
    "ws": true
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Mat backspin dialogue spinner

Our current setup involves using a progress spinner for each API call. The spinner is registered at the app module level, but we are facing an issue where the spinner hides behind the dialog popup. In order to solve this problem, we have decided to includ ...

Tips for showing more rows by clicking an icon within an Angular 2 table

When I click on the plus (+) button in the first column of each row, only one row expands. How can I modify it to expand multiple rows at a time? Thanks in advance. <div> <table class="table table-striped table-bordered"> <thead> ...

The appearance of the keyword 'private' caught me off guard. Is this a Typescript error at line 13,

Greetings, my eslint seems to be throwing an error at me for some unknown reason. https://i.sstatic.net/u0FF1.png Lines 12-14 constructor( private readonly box2D: typeof Box2D & EmscriptenModule, private readonly helpers: Helpers, This is h ...

Using the moment library in Angular to convert date and time can sometimes lead to errors

Whenever I attempt to convert a Gregorian date to a Persian date, the minute value in the conversion ends up becoming an error. For instance, let's say I want to convert this specific date and time to a Persian date: 2020-09-14T16:51:00+04:30 should ...

"Facing an issue where ts-node is not recognizing d.ts files, despite tsc being able to compile them

I am currently using typescript along with express and attempting to enhance the request object in express. Below is my server.ts file: import express, { Request, Response } from "express"; const app = express(); app.use(function(req: Request, res: Respo ...

Issue: Encounter StaticInjectorError while working with deployed Angular CLI project

We encountered an issue while attempting to deploy our Angular CLI (v.1.7.1) project on GitHub Pages and Firebase, resulting in the same outcome for both platforms. The ng serve command functions flawlessly on localhost:4200, and everything goes smoothly ...

Resolving a persistent AngularJS 1 constant problem with Typescript

I'm currently developing an application using TypeScript and AngularJS 1, and I've encountered a problem while trying to create a constant and passing it to another class. The constant in question is as follows: module app{ export class A ...

The Redux Store seems to be holding onto the initial state and not updating, even though the actions are functioning correctly

Upon successful authentication, the actions and reducer are updating correctly, but the mapstatetoprops function is not reflecting the changes in the new reducer state. Despite updates, the Store continues to log the initial state with each update. impor ...

establishing the default value as p-multiselect

Here is the code snippet I am currently working on: export class LkBoardStatus { id : number = 0; descr : string = ''; } In the component.ts file, I have defined the following: //... lkBoardStatusList: LkBoardStatus[] = []; selectedStat ...

Experimenting with a Collection of Items - Jest

I need to conduct a test on an array of objects. During the test coverage analysis of the displayed array, I found that the last object with the key link has certain conditions that are not covered. export const relatedServicesList: IRelatedServiceItem[ ...

Unit testing Firebase function with Jest for mocking

Currently, I am in the process of developing unit tests and facing challenges with mocking Firebase functions while specifying the return type upon calling them. The code snippet below illustrates what I intend to mock (account.service.ts) and provides ins ...

Unable to import necessary modules within my React TypeScript project

I am currently building a React/Express application with TypeScript. While I'm not very familiar with it, I've decided to use it to expand my knowledge. However, I've encountered an issue when trying to import one component into another comp ...

NG2-Charts are not rendering until the page is manually refreshed

I am currently working on an Angular project utilizing Angular 11. The issue I am encountering pertains to ng2-charts. Essentially, the chart is populated with data from an api-request call to the backend. I have identified where the problem lies, but I ...

Error: [X] does not behave like a function

I am utilizing angular4 along with dc.js to generate drill down charts. Here is the snippet of the code I am using: import { Component, ViewChild } from '@angular/core'; import { OnInit, AfterViewInit } from '@angular/core/src/metadata/lif ...

Setting up state using the useState hook in a Typescript environment

At some point in the future, the state will be updated using the useState hook with an array of objects. The interface for this array of objects will look like this: export interface DataSource { dataPiont: Array<DataPoint>; } export interface Dat ...

Unlocking the Power of Azure Key Vault with Angular for Securing Your Secrets

Can Azure Key Vault be utilized to retrieve a vault access secret within an Angular application? I am currently building with Azure Active Directory using implicit flow, which means I am developing everything without a backend. Within my Angular project, ...

How come the hasOwnProperty function does not remove objects of type {}?

I am working with a complex type called ReactNode from the version @types/react 16.9.17 and TypeScript v3.7.4. import React, { ReactNode } from 'react'; My goal is to reduce this type to a new type that includes the property children. To achie ...

simulate express-jwt middleware functions for secure routes

I am currently facing an issue with my code snippet, which looks like this: import app from '../src/app'; beforeAll(() => jest.mock('../src/middleware/auth', () => (req: Request, res: Response, next: NextFunction) => { ...

Implementing ngClass with a dynamic ID in the URL condition

I am attempting to create an ngClass condition that adds an active class to a list element. Specifically, I want it to work for both the URLs '/companies' and '/company/:id'. The issue I am facing is that the current setup does not fun ...

Converting keyValue format into an Array in Angular using Typescript

Is there a way to change the key-value pair format into an array? I have received data in the following format and need to convert it into an array within a .TS file. countryNew: { IN: 159201 BD: 82500 PK: 14237 UA: 486 RU: 9825 } This needs to be transf ...