在Angular 2应用程序中注入websocket服务时出错

时间:2018-02-23 14:48:45

标签: typescript rxjs angular2-services

我需要在Angular 2项目中处理websocket连接

@Injectable()
export class WsManagerService<T> extends Subject<T> {
    private socket: WebSocketSubject<any>;

    constructor() {
      super();
      ...

      this.connect();
    }

    connect(): void {
      this.socket = new WebSocketSubject(this.wsSubjectConfig);
      this.socket.subscribe(
        (m) => {
          this.handleMessage(m);
          this.next(m); /// when receiving a message, we just send it to Subject
        },
        (error: Event) => {
          if (!this.socket) {
            /// in case of an error with a loss of connection, we restore it
            this.reconnect();
          }
        });
    }

    handleMessage(message: any): void {
        if (this.isMessageConfiguration(message)) {
            // STORE GLOBAL VARIABLE
        } else if (this.isDateTime(message)) {
            ...
        }
    }

    isMessageConfiguration(object: any): object is MessageConfiguration {
        return 'rows' in object;
    }
}

我需要存储一个表示全局变量中配置的消息,以便组件可以检索它。

我以这种方式在组件中使用此服务

@Component({
  selector: 'app-map-setup',
  templateUrl: './map-setup.component.html',
  styleUrls: ['./map-setup.component.css'],
  providers: [WsManagerService]
})
export class MapSetupComponent {
    constructor (wsManagerService: WsManagerService) {}
}

但我无法解决“通用类型WsManagerService需要1类型参数”错误

我哪里错了?

1 个答案:

答案 0 :(得分:1)

由于WsManagerService服务类是泛型类,因此它在组件类的构造函数中注入它时需要一个类型。如果您不确定之前的类型,可以使用any作为类型。您的组件类代码应如下所示 -

@Component({
  selector: 'app-map-setup',
  templateUrl: './map-setup.component.html',
  styleUrls: ['./map-setup.component.css'],
  providers: [WsManagerService]
})
export class MapSetupComponent {
    constructor (private wsManagerService: WsManagerService<any>) {} // change it here
}

这是一个有效的演示:https://stackblitz.com/edit/angular-fjdmlw