Adi*_*dil 1 sockets dependency-injection typescript 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"));
}
}
Run Code Online (Sandbox Code Playgroud)
这是模块文件
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 { }
Run Code Online (Sandbox Code Playgroud)
这是服务文件
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"));
}
}
Run Code Online (Sandbox Code Playgroud)
任何可以解决此错误的人。
您在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 { }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13267 次 |
| 最近记录: |