在 socket.io-client 中调用 IO 时出错,角度为 8

Dak*_*ksh 3 socket.io angular

我在我的 angular 项目中调用 socket.io-client 的 IO,如下所示:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/internal/Observable';
import * as io from 'socket.io-client';
@Injectable({
  providedIn: 'root'
})
export class SocketclientService {
  socket:any;
  url:any="ws://localhost:8080"
  constructor() {
    this.socket = io(this.url);
   }
   
   listen(eventname:any,data:any){
     return new Observable((subscriber)=>{
       this.socket.on(eventname,(data:any)=>{
         subscriber.next(data);
       })
     })
   }
   emit(eventname:string,data:any){
     this.socket.emit(eventname,data);
   } 
}
Run Code Online (Sandbox Code Playgroud)

但我总是收到这样的错误:

 Error: src/app/services/socketclient.service.ts:11:19 - error TS2349: This expression is not callable.
      Type 'typeof import("C:/somepathtoproject/node_modules/socket.io-client/build/index")' has no call signatures.
    
    11     this.socket = io(this.url);
                         ~~
Run Code Online (Sandbox Code Playgroud)

我不明白为什么会这样显示,即使我已经安装了 @types/socket.io-client

jua*_*iza 19

在 angular 10 中工作正常:

import {io} from 'socket.io-client';
Run Code Online (Sandbox Code Playgroud)

这是官方文档 https://socket.io/docs/v3/client-api/index.html

  • VSCode 向我发出以下警告:`模块 '"socket.io-client"' 没有导出成员 'io'.ts(2305)` 但一切正常。 (4认同)
  • @ViniciusArruda 和其他人:这是由手动安装的类型定义引起的。但它们现在包含在 npm 包中。所以只需删除它们:`npm uninstall @types/socket.io-client`。 (3认同)
  • 这应该被接受的答案。完美运作 (2认同)

Mar*_*der 7

这可能是由单独安装的类型定义引起的。但是它们现在随socket.io-client包一起提供(请参阅文档:“TypeScript 用户注意事项”)。

所以只需卸载它们并更改导入:

npm uninstall @types/socket.io-client

import { io, Socket } from 'socket.io-client';
Run Code Online (Sandbox Code Playgroud)


小智 6

我找到了一个解决方法,我探索了 socket.io-client 模块,在“index.d.ts”下我找到了这一行:

export { lookup as io, Socket, SocketOptions };
Run Code Online (Sandbox Code Playgroud)

所以我尝试像这样导入:

import {io} from 'socket.io-client/build/index';
Run Code Online (Sandbox Code Playgroud)

然后使用它:

this.socket=io(url);
Run Code Online (Sandbox Code Playgroud)

它对我有用。