我在我的 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
这可能是由单独安装的类型定义引起的。但是它们现在随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)
它对我有用。
| 归档时间: |
|
| 查看次数: |
8793 次 |
| 最近记录: |