【问题标题】:Error when injecting websocket service in Angular 2 application在 Angular 2 应用程序中注入 websocket 服务时出错
【发布时间】:2018-02-23 14:48:45
【问题描述】:

我需要在我的 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 个类型参数”错误

我哪里错了?

【问题讨论】:

  • 检查我的答案应该可以解决您的编译问题。

标签: typescript rxjs angular2-services


【解决方案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

【讨论】:

  • 谢谢@Niladri,这解决了问题,但我有一个新的Uncaught (in promise): Error: StaticInjectorError[String]: StaticInjectorError[String]: NullInjectorError: No provider for String!
  • @Marco24690 是否与providers: [WsManagerService] 有关?你在哪里得到错误?
  • @Marco24690 可以尝试更新providers:[ {provide:'WbSocketService', useFactory:()=&gt;(new WsManagerService&lt;any&gt;())}] 并将构造函数更改为constructor (@Inject('WbSocketService') private wsManagerService: WsManagerService&lt;any&gt;) {}
  • 我在添加构造函数constructor (private wsManagerService: WsManagerService&lt;any&gt;)的参数时出现错误尝试了您提出的解决方案,但是现在我在构造函数中出现此编译错误Expected 1-5 arguments, but got 0. src/app/map-setup/map-setup.component.ts(32,16): error TS2304: Cannot find name 'Inject'
  • 您是否从@angular/core 导入{inject }
猜你喜欢
  • 2016-10-25
  • 1970-01-01
  • 1970-01-01
  • 2017-08-24
  • 2021-11-23
  • 2014-03-09
  • 2016-12-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多