angulartypescriptstompsockjs

Angular module not found


I was working on a chat for my project using sockJS and STOMP, after various difficulties with installing the 2 libraries I thought I did that (I tried doing that from index.html, npm install and even downloaded 2 min files and put them in the assets folder), after a while I added

import * as Stomp from 'stompjs';

import * as SockJS from 'sockjs-client';

and I received no more errors in my typescript file (actually it still gave me errors on those import declarations but I clicked on a quick fix 'download missing types' and it solved itself so basically I in some way that I don't know installed those things)

so I kept working on my code in a minimal way just to do a quick test, and wouldn't you know it when I was done and ran the project it didn't work

it gave me this error

./node_modules/stompjs/lib/stomp-node.js:14:8-22 - Error: Module not found: Error: Can't resolve 'net' in 'C:\Users\UTENTE\Desktop\CORSO AZIENDA FORMAZIONE\angular-projects\gestionaleFrontEnd\node_modules\stompjs\lib'

I have no clues on how to fix this so I'm just going to leave here my stuff hoping you guys will help me

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { User } from '../model/user';
import { UserService } from '../user.service';
import * as Stomp from 'stompjs';
import * as SockJS from 'sockjs-client';
import { FormControl } from '@angular/forms';

@Component({
  selector: 'app-chat',
  templateUrl: './chat.component.html',
  styleUrls: ['./chat.component.css'],
})
export class ChatComponent implements OnInit {
  url = 'http://localhost:8080';
  otherUser?: User;
  thisUser: User = JSON.parse(sessionStorage.getItem('user')!);
  channelName?: string;
  socket?: WebSocket;
  stompClient?: Stomp.Client;
  newMessage = new FormControl('');

  constructor(
    private route: ActivatedRoute,
    private userService: UserService
  ) {}

  ngOnInit(): void {
    this.userService
      .getUserByNickname(this.route.snapshot.paramMap.get('user')!)
      .subscribe((data) => {
        this.otherUser = data;
        this.connectToChat();
      });
  }

  connectToChat() {
    const id1 = this.thisUser.id!;
    const nick1 = this.thisUser.nickname;
    const id2 = this.otherUser?.id!;
    const nick2 = this.otherUser?.nickname!;

    if (id1 > id2) {
      this.channelName = nick1 + '&' + nick2;
    } else {
      this.channelName = nick2 + '&' + nick1;
    }

    console.log('connecting to chat...');
    this.socket = new SockJS(this.url + '/chat');
    this.stompClient = Stomp.over(this.socket);

    this.stompClient.connect({}, (frame) => {
      //func = what to do when connection is established
      console.log('connected to: ' + frame);
      this.stompClient!.subscribe(
        '/topic/messages/' + this.channelName,
        function (response) {
          //func = what to do when client receives data (messages)
          let data = JSON.parse(response.body);
          console.log(data);
        }
      );
    });
  }

  //String sender, String t_stamp, String content
  sendMsg() {
    if (this.newMessage.value !== '') {
      this.stompClient!.send(
        '/app/chat/' + this.channelName,
        {},
        JSON.stringify({
          sender: this.thisUser.nickname,
          t_stamp: 'to be defined in server',
          content: this.newMessage.value,
        })
      );
    }
  }
}

next is the app.module.ts where the error most likely is idk

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { ReactiveFormsModule } from '@angular/forms';
import { RegistrationComponent } from './registration/registration.component';
import { HomeComponent } from './home/home.component';
import { ConfirmationComponent } from './confirmation/confirmation.component';
import { LoginComponent } from './login/login.component';
import { UserComponent } from './user/user.component';
import { UserHomeComponent } from './user-home/user-home.component';
import { NewAnnuncioComponent } from './new-annuncio/new-annuncio.component';
import { MyAnnunciComponent } from './my-annunci/my-annunci.component';
import { EditAnnuncioComponent } from './edit-annuncio/edit-annuncio.component';
import { SearchComponent } from './search/search.component';
import { SearchResultComponent } from './search-result/search-result.component';
import { OtherUserComponent } from './other-user/other-user.component';
import { OtherAnnunciComponent } from './other-annunci/other-annunci.component';
import { ViewAnnuncioComponent } from './view-annuncio/view-annuncio.component';
import { ProvaFileComponent } from './prova-file/prova-file.component';
import { FormsModule } from '@angular/forms';
import { QAndAComponent } from './q-and-a/q-and-a.component';
import { ChatComponent } from './chat/chat.component';



@NgModule({
  declarations: [
    AppComponent,
    RegistrationComponent,
    HomeComponent,
    ConfirmationComponent,
    LoginComponent,
    UserComponent,
    UserHomeComponent,
    NewAnnuncioComponent,
    MyAnnunciComponent,
    EditAnnuncioComponent,
    SearchComponent,
    SearchResultComponent,
    OtherUserComponent,
    OtherAnnunciComponent,
    ViewAnnuncioComponent,
    ProvaFileComponent,
    QAndAComponent,
    ChatComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    ReactiveFormsModule,
    HttpClientModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

next is package.json, because blip me that's why

{
  "name": "gestionale-front-end",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "watch": "ng build --watch --configuration development",
    "test": "ng test"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~12.1.0",
    "@angular/common": "~12.1.0",
    "@angular/compiler": "~12.1.0",
    "@angular/core": "~12.1.0",
    "@angular/forms": "~12.1.0",
    "@angular/platform-browser": "~12.1.0",
    "@angular/platform-browser-dynamic": "~12.1.0",
    "@angular/router": "~12.1.0",
    "rxjs": "~6.6.0",
    "sockjs": "^0.3.21",
    "sockjs-client": "^1.5.2",
    "stompjs": "^2.3.3",
    "tslib": "^2.2.0",
    "zone.js": "~0.11.4"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~12.1.4",
    "@angular/cli": "~12.1.4",
    "@angular/compiler-cli": "~12.1.0",
    "@types/jasmine": "~3.8.0",
    "@types/node": "^12.11.1",
    "@types/sockjs-client": "^1.5.1",
    "@types/stompjs": "^2.3.5",
    "jasmine-core": "~3.8.0",
    "karma": "~6.3.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.0.3",
    "karma-jasmine": "~4.0.0",
    "karma-jasmine-html-reporter": "~1.7.0",
    "typescript": "~4.3.2"
  }
}

if y'all need me to show you more stuff just tell me

EDIT: I found this which was exactly my case https://github.com/jmesnil/stomp-websocket/issues/119 so I tried their solution (npm i net -s)

now I only see the index.html and on the browser console I got

Uncaught ReferenceError: global is not defined at Object.5103 (vendor.js:74896)
    at __webpack_require__ (runtime.js:23)
    at Object.8263 (vendor.js:75368)
    at __webpack_require__ (runtime.js:23)
    at Object.9834 (vendor.js:75023)
    at __webpack_require__ (runtime.js:23)
    at Object.4014 (vendor.js:74613)
    at __webpack_require__ (runtime.js:23)
    at Object.1428 (vendor.js:72979)
    at __webpack_require__ (runtime.js:23)

this is extremely frustrating


Solution

  • Add

    (window as any).global = window;
    

    to the polifills file.