问题
Hi i am trying to use socket.io in my angular project. there are three files which i am going to show which are component file and one service file and one module file. when ever i use service in my component file i get the static injector error. which is:
Error: StaticInjectorError(AppModule)[AppComponent -> WrappedSocket]: StaticInjectorError(Platform: core)[AppComponent -> WrappedSocket]:
NullInjectorError: No provider for WrappedSocket!
Here is the Component file:
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"));
}
}
Here is the Module file
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 { }
Here is the service file
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"));
}
}
any one who can solve this error.
回答1:
You're missing an import in your 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 { }
来源:https://stackoverflow.com/questions/50233403/type-script-angular-static-injector-error