Javascript 如何在 angular 2 应用程序中导入 socket.io-client?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37090031/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:54:03  来源:igfitidea点击:

How to import socket.io-client in a angular 2 application?

javascriptangularsocket.io

提问by simonaco

I want to include sockets.io-client in my angular 2 application. First I installed socket.io-client, installed typings:

我想在我的 angular 2 应用程序中包含 sockets.io-client。首先我安装了socket.io-client,安装了typings:

npm install socket.io-client --save
typings install socket.io-client --save --ambient

Next step was to include socket.io-client into my index.html:

下一步是将 socket.io-client 包含到我的 index.html 中:

 <script src="node_modules/socket.io-client/socket.io.js"></script>

In my component, I am importing sockets.io:

在我的组件中,我正在导入 sockets.io:

import * as io from 'socket.io-client'

And then using it:

然后使用它:

var socket = io('http://localhost:3000');
socket.on('event', function(data:any){
   console.log(data);
}.bind(this)); 

This fails with:

这失败了:

zone.js:101 GET http://localhost:3001/socket.io-client 404 (Not Found)
(index):18 Error: Error: XHR error (404 Not Found) loading http://localhost:3001/socket.io-client

Any ideas?

有任何想法吗?

采纳答案by Abdulrahman Alsoghayer

In order to register the module so you can import it, you need to include it in you SystemJS configuration.

为了注册模块以便您可以导入它,您需要将它包含在您的 SystemJS 配置中。

System.config({
    packages: {
        ...
        "socket.io-client": {"defaultExtension": "js"}
    },
    map: {
        "socket.io-client": "node_modules/socket.io-client/socket.io.js"
    }
});

And change your import to:

并将您的导入更改为:

import io from 'socket.io-client';
import * as io from "socket.io-client

import io from 'socket.io-client';
import * as io from "socket.io-client

Also, you don't need the import in the script tag anymore, so remove:

此外,您不再需要脚本标签中的导入,因此删除:

<script src="node_modules/socket.io-client/socket.io.js"></script>

Finally, if you like to add the typings, add in your typings.json:

最后,如果您想添加类型,请添加typings.json

{
  "ambientDependencies": {
    ...
    "socket-io-client":"github:DefinitelyTyped/DefinitelyTyped/socket.io-client/socket.io-client.d.ts#7de6c3dd94feaeb21f20054b9f30d5dabc5efabd"
  }
}

P.S. Int the future, change the hash in the typings to the latest commit hash.

PS Int 将来,将typings 中的hash 更改为最新的commit hash。

回答by Lucas

This is a late answer since I just had this problem and installing correct types via npmsolved it for me:

这是一个迟到的答案,因为我刚刚遇到了这个问题并且通过 npm安装正确的类型为我解决了这个问题 :

npm install @types/socket.io-client --save

This package contains type definitions for socket.io-client, so if you are getting type errors this should fix it.

此包包含 的类型定义socket.io-client,因此如果您遇到类型错误,这应该修复它。

回答by Wetteren Rémi

I also had problems while trying to import socket.io into my project and here is how I resolved it.

我在尝试将 socket.io 导入我的项目时也遇到了问题,这是我解决的方法。

Here we go :

开始了 :

1) Edit your systemjs.config.js file as it :

1) 编辑您的 systemjs.config.js 文件:

/**
 * System configuration for Angular 2 samples
 * Adjust as necessary for your application needs.
 */
(function (global) {
  System.config({
    paths: {
      // paths serve as alias
      'npm:': 'node_modules/'
    },
    map: {
      ... here my stuff ...
      "socket.io-client": 'npm:socket.io-client'
    },
    packages: {
      ... here my stuff ...
      "socket.io-client": {
        main: './socket.io.js'
      }
    }
  });
})(this);

2) Open your project in a shell then exec the following line : usually we tell you to do :

2)在shell中打开你的项目然后执行以下行:通常我们告诉你这样做:

npm install socket.io-client --save
typings install socket.io-client --save --ambient

But you might received a message that told you that the ambiant flag is deprecated and that you should use global instead. But you'll quickly see that it won't work either. So i propose you something else (well errors logs will give you hints, but you probably won't understand it if you didn't go therebefore) :

但是您可能会收到一条消息,告诉您环境标志已被弃用,您应该使用 global 来代替。但是你很快就会发现它也行不通。所以我向你推荐其他东西(错误日志会给你提示,但如果你以前不去那里你可能不会理解它):

typings install dt~socket.io-client --save --global

3) Open your component that require socket.io then add at the top of your file :

3) 打开需要 socket.io 的组件,然后在文件顶部添加:

import * as io from "socket.io-client";

then go down and add :

然后往下添加:

export class MessageComponent implements OnInit {
  socket:any = null;

  constructor() {
      this.socket = io('http://localhost:1337');
  }
  ... here my stuff ...
}

Where 1337 is the port of your node server containing socket.io that has been launched.

其中 1337 是包含已启动的 socket.io 的节点服务器的端口。

Now, all is ready, you can directly make your request :

现在,一切就绪,您可以直接提出您的请求:

this.socket.emit('sendMessage', {content:'it works !'});

Hope I help :), good luck with your project

希望我能帮助:),祝你的项目好运

回答by Chris

angular-cli: 0.0.39 
node: 6.2.2 
os: win32 x64

I tried to import socket.io-client into an angular2 app generated with the angular-clibut i can't get it to work.

我试图将 socket.io-client 导入到使用angular-cli生成的 angular2 应用程序中,但我无法让它工作。

chat.component.ts

聊天组件.ts

import * as io from "socket.io-client";

@Component({
  ...
})
export class ChatAppComponent {
  ...
}

system-config.ts

系统配置文件

/** Map relative paths to URLs. */
const map: any = {
    "socket.io-client": "vendor/socket.io-client/socket.io.js"
};

/** User packages configuration. */
const packages: any = {
    "socket.io-client": {"defaultExtension": "js"}
};

angular-cli-build.js

angular-cli-build.js

var Angular2App = require('angular-cli/lib/broccoli/angular2-app');

module.exports = function(defaults) {
  return new Angular2App(defaults, {
    vendorNpmFiles: [
      'systemjs/dist/system-polyfills.js',
      'systemjs/dist/system.src.js',
      'zone.js/dist/*.js',
      'es6-shim/es6-shim.js',
      'reflect-metadata/*.js',
      'rxjs/**/*.js',
      '@angular/**/*.js',
      'socket.io-client/socket.io.js'
    ]
  });
};

package.json

包.json

{
      "dependencies": {
        ...
        "socket.io-client": "^1.4.8",
        "systemjs": "0.19.26"
      },
      "devDependencies": {
        ...
        "typescript": "^1.8.10",
        "typings": "
      }
}

typings.json

打字.json

{
  "ambientDevDependencies": {
    "angular-protractor": "registry:dt/angular-protractor#1.5.0+20160425143459",
    "jasmine": "registry:dt/jasmine#2.2.0+20160412134438",
    "selenium-webdriver": "registry:dt/selenium-webdriver#2.44.0+20160317120654"
  },
  "ambientDependencies": {
    "es6-shim": "registry:dt/es6-shim#0.31.2+20160317120654",
  },
  "globalDependencies": {
    "socket.io-client": "registry:dt/socket.io-client#1.4.4+20160317120654"
  }
}