Search code examples
websocketdependency-injectionrxjsangular13

Why I'm not able to Inject this service?


Here's my websocket.service.ts on my Angular 13 application:

import { Injectable } from "@angular/core";
import { Subject, Observable, Observer } from 'rxjs';

@Injectable()
export class WebsocketService {
    private subject: Subject<MessageEvent>;

    constructor() { }

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

        return this.subject;
    }

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

        let observable = new Observable((obs: 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 Subject.create(observer, observable);
    }
}

But when I try to Inject it on a Component:

import { WebsocketService } from "../../../services/websocket.service";
import { Subject } from 'rxjs';
import { map } from 'rxjs/operators';

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

constructor(
    private appConfigService: AppConfigService,
    public ws: WebsocketService
) {
    this.messages = <Subject<Message>>ws.connect(this.appConfigService.wsUrl).pipe(
        map((response: MessageEvent): Message => {
            let data = JSON.parse(response.data);

            return {
                author: data.author,
                message: data.message
            };
        })
    );
}

I got this error:

enter image description here

Can't Inject this kind of Service? Not sure where's the problem...


Solution

  • You probably need to use this form of Injectable decorator

    @Injectable({ providedIn: 'root', })