【问题标题】:Type script - angular : static injector error打字稿 - 角度:静态注入器错误
【发布时间】:2018-10-18 09:26:03
【问题描述】:

您好,我正在尝试在我的 Angular 项目中使用 socket.io。 我将展示三个文件,它们是组件文件、一个服务文件和一个模块文件。每当我在组件文件中使用服务时,都会出现静态注入器错误。 即:

错误:StaticInjectorError(AppModule)[AppComponent -> WrappedSocket]: StaticInjectorError(Platform: core)[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"));              
    }
}

任何能解决这个错误的人。

【问题讨论】:

  • 请重新格式化您的代码。删除空行并将代码缩进 4 个空格
  • 您好,欢迎来到 StackOverflow!请尝试格式化您的代码,它有助于人们阅读和理解您的问题,并增加有人回答您的可能性。 meta.stackexchange.com/help/formatting

标签: angular typescript sockets dependency-injection


【解决方案1】:

您的 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 { }

【讨论】:

    猜你喜欢
    • 2017-05-29
    • 2023-03-29
    • 2020-06-08
    • 2015-03-21
    • 1970-01-01
    • 2019-06-08
    • 2019-04-09
    • 2015-06-23
    • 2013-08-16
    相关资源
    最近更新 更多