Encountering a 403 error with RXJS when attempting to subscribe to a websocket in Angular

I am currently searching for a resolution to this issue without making any upgrades to Angular or its dependencies, as it could potentially impact other parts of the code base

https://i.sstatic.net/Jeb55.png

package.json

{
  "name": "angular4",
  "version": "1.0.0",
  "description": "QuickStart package.json from the documentation for visual studio 2017 & WebApi",
  "scripts": {
    "start": "tsc && concurrently \"tsc -w\" \"lite-server\" ",
    ...
    
    // (truncated for brevity)
  },
  ...
}

https://i.sstatic.net/fDcbH.png

search.component.ts

import { Subject, Subscription } from "rxjs";
import { WebSocketSubject } from "rxjs/observable/dom/WebSocketSubject";
import { webSocket } from "rxjs/observable/dom/webSocket";
   public openWebSocket = async (uniqueId: string) => {
    const url: string = this.commonService.wssurl + '/api/ABCWebSocket/' + uniqueId;
    let socket: WebSocketSubject<any> = webSocket(url);
    
    
    // (truncated for brevity)
  };

code snippet causing the error - Guess the Subscribe part throws the error as when commenting it out it works fine https://i.sstatic.net/lrtZY.png

The backend is a .Net project btw. Went through few answer in few forums but did not get what I expect as am not trying to update the packages

Answer №1

If you find yourself without a constraint driving you, consider creating your own wrapper using RxJs for websockets. However, don't forget that RxJs already offers its native solution for websockets. This built-in wrapper provides support for:

1- Listening

2- Pushing

3- Multiplexing

Take a look at this example of how to use an RxJs websocket to listen to the server:

import { webSocket } from 'rxjs/webSocket';

const subject = webSocket('ws://localhost:8081');

subject.subscribe({
  next: msg => console.log('message received: ' + msg), // Triggered when a message is received from the server.
  error: err => console.log(err), // Executed if WebSocket API encounters an error.
  complete: () => console.log('complete') // Invoked when the connection is closed.
 });

Answer №2

Just an update - after some troubleshooting, I discovered that the issue stemmed from using an outdated version of Angular 5 and an incorrect approach to subscribing to the websocket. Here's a more reliable method using observables:

this.url = this.commonVariables.wssurl + '/api/AbcApi/' + id;
    this.wsService.createObservableSocket(this.url)
        .subscribe(
            data => {
                //TODO After received Response
                console.log('message from server with id: ' + data);
                this.UpdateUi(data);
            },
            err => console.log(err),
            () => console.log('The observable stream is complete')
    );

To implement this in the websocket.service class:

import { Observable } from "rxjs/Rx";

export class WebSocketService { ws: WebSocket;

createObservableSocket(url: string): Observable<string> {
    console.log('created observable socket');
    this.ws = new WebSocket(url);
    return new Observable(observer => {
        this.ws.onmessage = (event) => observer.next(event.data);
        this.ws.onerror = (event) => observer.error(event);
        this.ws.onclose = (event) => observer.complete();
    });
}
sendMessage(message: any) {
    this.ws.send(message);
}

}

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

ts:Accessing the state within a Redux store

In my rootReducer, I have a collection of normal reducers and slice reducers. To access the state inside these reducers, I am using the useSelector hook. Here is my store setup : const store = configureStore({reducer : rootReducer}); Main Reducer: const ...

Is there a way to locate all projects impacted by `nx`?

Currently, I am utilizing the nx tool to manage a mono repo specifically designed for typescript projects. The nx comes equipped with a command called affected, which allows me to focus solely on the changed project and any other projects that rely on it. ...

What is the best way to implement multiple HTTP subscriptions in a loop using Angular?

I find myself in a predicament where I need to iterate through an array of strings passed as parameters to a service, which then responds through the HTTP subscribe method. After that, some operations are performed on the response. The issue arises when t ...

TypeB should utilize InterfaceA for best practice

I have the following TypeScript code snippet. interface InterfaceA { id: string; key: string; value: string | number; } type TypeB = null; const sample: TypeB = { id: '1' }; I am looking for simple and maintainable solutions where TypeB ...

Having trouble resolving React within the Formik/dist package due to a custom webpack configuration

Struggling to set up projects from scratch, encountering an issue with webpack not being able to resolve formik's modules while other third-party modules like styled-components work fine. I've tried searching online for a solution but couldn&apos ...

Exploring Angular's nested Routing within dynamically loading Modules using a specific router-outlet reference

I am currently experimenting with nested routing while utilizing a named router-outlet for managing the routing in my side-bar navigation. Within my main module, I have loaded the nav-component which contains a named router-outlet within its template: &l ...

Tips for adjusting the size of a textarea to perfectly fit within a table cell

I have a textarea displayed within an input in a table, but I am looking to resize it so that it completely fills the table cell up to the borders. Here is the logic: <textarea type="textarea" value="{{data.directRowNo}}" id = " ...

.NET Third-Party Oracle Providers offering object type support

Currently in search of a third-party Oracle Data Provider for .Net (ADO.NET) that fully supports Oracle object types, including geometries. My initial choice of ODP.NET has proven to be extremely buggy and I am now facing the consequences - constant cras ...

Typescript libraries built specifically for unique custom classes

I am currently exploring the most effective method for creating a class library in Typescript and deploying it to NPM along with a definitions file. The classes within the library serve as models that are utilized by multiple RESTful services. Some of the ...

Decoding Facebook JSON Game Invitation Information

Currently, I am utilizing Facebook's platform and have implemented a callback method that returns the JSON result as a string. This is an example of the format for the returned result: { "request": "420211088059698", "to": [ "100002669403922", ...

Personalizing the appearance controls of A-frame with a unique TypeScript-written custom component?

Currently, I am in the process of developing custom look controls for A-Frame based on their official documentation. This custom component is being written in TypeScript as part of an Angular project that enforces tslint rules restricting the use of this o ...

What is the correct way to link an array with ngModel using ngFor loop in Angular?

Utilizing ngModel within an ngFor iteration to extract values from a single input field like this : <mat-card class="hours" > <table id="customers"> <thead > <th >Project</th> ...

Is it possible to set restrictions with the Calendar Extender?

I am facing a challenge with my calendar extension and finding it difficult to solve on my own. I want to limit the feature to show only the current month and the previous month. Can someone provide assistance with this issue, if possible? ...

Tips for enlarging the font size of a number as the number increases

Utilizing the react-countup library to animate counting up to a specific value. When a user clicks a button, the generated value is 9.57, and through react-counter, it visually increments from 1.00 to 9.57 over time. Here's the code snippet: const { ...

Access the JSON data containing sub array values and showcase them on an HTML page by utilizing ngFor

Greetings! I am currently working on a web application where I need to showcase student data that is being received in JSON format. Below is the TypeScript code snippet that outlines the structure of the student data: export interface studentData{ ...

Discover which references are yet to be resolved within a tsx file

I have been tasked with developing a custom builder for a web application. The challenge now is to automatically detect imports in the code so that the right modules can be imported. My current solution involves traversing the AST of the scripts, keeping ...

Why does my WCF REST web service escape the JSON string response for weakly-typed JSON?

I am currently working with a contract that looks like this: [ServiceContract] public interface IServiceJsonContract { [WebInvoke(UriTemplate = "/MyMethod", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, Method = "POST" ...

Multiple WAR files are nestled within an EAR file, facilitating the sharing of classes

Currently, my development setup involves Eclipse Neon and Maven. My projects consist of two main entities: Project 1 for all the Web services (SOAP and RESTful) and database access implementations, and Project 2 which houses the Angular implementation for ...

Angular and Bootstrap combined to create a versatile navigation bar with a collapsible sidebar feature

Currently, I am in the process of developing a progressive web app using Angular and Bootstrap. One of the main challenges I am facing is implementing a navbar that not only looks great on desktop but also on mobile devices. So far, I am satisfied with my ...

TypeScript - the object may potentially be 'null'

Despite receiving an error message, the program is running perfectly. https://i.sstatic.net/4NQyR.jpg var video = document.querySelector('#camera-stream'), if(!navigator.getMedia){ displayErrorMessage("Your browser doesn't have su ...