Typescript - 角度:静态注入器错误

2024-01-03

您好,我正在尝试在我的 Angular 项目中使用 socket.io。 我将展示三个文件,分别是组件文件、一个服务文件和一个模块文件。当我在组件文件中使用服务时,我会收到静态注入器错误。 这是:

错误:StaticInjectorError(AppModule)[AppComponent -> WrappedSocket]: StaticInjectorError(平台:核心)[AppComponent -> WrappedSocket]:
NullInjectorError:没有 WrappedSocket 的提供者!

这是组件文件:

import { Component } from '@angular/core';   
import {  cheema2 } from './practice.service';
import { Injectable } from '@angular/core';
import { Socket } from 'ng-socket-io';

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

 @Injectable()    
 export class AppComponent  
 {   
     constructor(private socket: Socket) { }

     sendMessage(msg: string){
     this.socket.emit("message", msg);
   }

   getMessage() 
   {
     console.log( this.socket.fromEvent("message"));
   }

}

这是模块文件

import { BrowserModule } from '@angular/platform-browser';   
import { NgModule } from '@angular/core';
import { SocketIoModule, SocketIoConfig } from 'ng-socket-io';

const config: SocketIoConfig = { url: 'http://localhost:4200', options: {}    
};       
import { AppComponent } from './app.component';

@NgModule
({  
declarations:
 [
   AppComponent
 ],
 imports: [
   BrowserModule
  ],
 providers: [],
 bootstrap: [AppComponent]
})

export class AppModule { }

这是服务文件

import { Injectable } from '@angular/core';  
import { Socket } from 'ng-socket-io';

@Injectable()
export class cheema2  
{
    constructor(private socket: Socket) { console.log("adil"); }

    sendMessage(msg: string){
       console.log("sharif");
       this.socket.emit("message", msg);
    }

    getMessage() {
      console.log( this.socket.fromEvent("message"));              
    }
}

任何能够解决此错误的人。


您的 AppModule 中缺少导入:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { SocketIoModule, SocketIoConfig } from 'ng-socket-io';
const config: SocketIoConfig = { 
  url: 'http://localhost:4200', options: {}
};

import { AppComponent } from './app.component';

@NgModule ({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    SocketIoModule.forRoot(config) <<< ADD THIS
  ],
  providers: [],
  bootstrap: [AppComponent] })
export class AppModule { }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Typescript - 角度:静态注入器错误 的相关文章

随机推荐