ngx-socket-io
ngx-socket-io copied to clipboard
BUG - Socket class is undefined
Hello everyone,
When I use the provideSocketIo provider instead of the Angular Module forRoot import, i get Socket is undefined when doing any type of operation on the socket class of ngx-socket-io.
-- app.config.ts
import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';
import { provideRouter } from '@angular/router';
import { SocketIoConfig, provideSocketIo } from 'ngx-socket-io';
import { routes } from './app.routes';
const config: SocketIoConfig = { url: 'http://localhost:3000', options: {} };
export const appConfig: ApplicationConfig = {
providers: [
provideZoneChangeDetection({ eventCoalescing: true }),
provideRouter(routes),
provideSocketIo(config)]
};
-- app.component.ts
@Component({
selector: 'app-root',
imports: [RouterOutlet, NgFor, AsyncPipe],
templateUrl: './app.component.html',
styleUrl: './app.component.scss',
})
export class AppComponent {
constructor(private socket: ChatService) {}
sendMessage(msg: string) {
this.socket.sendMessage(msg)
}
getMessage() {
return this.socket.getMessage()
}
}
-- chat.service.ts
import { Injectable } from '@angular/core';
import { Socket } from 'ngx-socket-io';
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class ChatService {
constructor(private socket: Socket) {
}
sendMessage(msg: string) {
this.socket.emit('message', msg);
}
getMessage() {
return this.socket.fromEvent('message').pipe(map(data => data.msg));
}
}