'No provider for $WebSocket angular5 with

I have some application which uses websockets, for that I was using angular2-websocket in my angular5 application. I keep getting following errors:

StaticInjectorError(AppModule)[AppComponent -> $WebSocket]:
StaticInjectorError(Platform: core)[AppComponent -> $WebSocket]:
NullInjectorError: No provider for $WebSocket!

My Component Ts File:

import { Component, OnInit } from '@angular/core';
import { $WebSocket, WebSocketSendMode } from 'angular2-websocket/angular2-websocket';


interface ChatModel {
  user: String;
  message: String;
}


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit {
  title = 'Websockets Chat Using Angular 2 Sockets And Django Channels';

  constructor(
    private mysocket: $WebSocket,
    public chatData: ChatModel[],
    public message: String,
    public user: String
  ) {}

  onChatSubmit() {
    const datatoSend = JSON.stringify({
      'user': this.user,
      'message': this.message
    });
    this.mysocket.send(datatoSend);

  }

  addChatItem(msg: MessageEvent) {
    this.chatData.push(
      JSON.parse(msg.data)
    );
  }

  ngOnInit() {
    /*
    this.mysocket = new $WebSocket('ws//127.0.0.01:8000');
    this.mysocket.setSend4Mode(WebSocketSendMode.Direct);

    this.mysocket.onMessage(this.addChatItem);
    */
  }
}

in app.module.ts file no providers array is empty



Solution 1:[1]

sounds like an issue with dependency injection.

Get rid of the Constructor injection on the private mysocket: $WebSocket

Angular is trying to find $Websocket from your module provider, but can't find any.

Not sure why you need to inject websocket in your constructor, if you do have a use case, then make sure you provide it in your module provider.

@NgModule({
  imports:      [ BrowserModule, FormsModule ],
  declarations: [ AppComponent, HelloComponent ],
  providers: [], //<-- need to provide websocket$
  bootstrap:    [ AppComponent ]
})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1