【问题标题】:How can we use socket.io with Angular.?我们如何将 socket.io 与 Angular 一起使用?
【发布时间】:2018-04-22 05:29:04
【问题描述】:

这是我的代码。我们如何在 Angular 中使用 socket.io?

import { Component } from '@angular/core';

import { createServer, Server } from 'http';

import * as express from 'express';

import * as socketIo from 'socket.io';





const SERVER_URL = 'localhost:4200';

@Component({




  selector: 'app-root',

  templateUrl: './app.component.html',

  styleUrls: ['./app.component.css']

})

export class AppComponent {


  public static readonly PORT:number = 8080;

  private app: express.Application;

  private server: Server;

  **"private io: SocketIO.server;"**  ////at this line i get error that cannot find namespace SocketIO

  private port: string | number;


}

我正在尝试在我的 Angular 应用程序中使用 socket.io。我在粗线处得到了错误。谁能帮我解释一下为什么会出现这个错误?

【问题讨论】:

  • 这与 Angular 无关。如果您使用的是 TypeScript,请阅读有关 TypeScript 的信息

标签: angular socket.io


【解决方案1】:

https://www.npmjs.com/package/ngx-socket-io

npm install ngx-socket-io

比 ng-socket-io 好,因为在 rxjs-compat 中就不需要了。

【讨论】:

  • 对不起,ng-socket-io 和 ngx-socket-io 有什么区别?
  • @VitaliyMarkitanov ngx-socket-io 使用 rxjs v6,它在 angular 6+(甚至可能是 5+,我不记得)项目中运行良好。 ng-socket-io 使用 rxjs v5,您需要安装 rxjs-compat 依赖项才能使 ng-socet-io 在 angular 6+ 项目中工作。
【解决方案2】:

这不是使用 Socket.io 的最佳方式,我建议你使用这个模块

https://github.com/bougarfaoui/ng-socket-io

在你的项目中安装它

npm install ng-socket-io

然后将其添加到您的应用模块中

import { SocketIoModule, SocketIoConfig } from 'ng-socket-io';

const config: SocketIoConfig = { url: 'http://localhost:8988', options: {} 
};

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    SocketIoModule.forRoot(config) 
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

然后你就可以在从injectable 扩展的服务中使用它了。

【讨论】:

    猜你喜欢
    • 2012-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-14
    • 2013-02-22
    • 2017-01-24
    • 2017-08-23
    相关资源
    最近更新 更多