typescript 如何将 SockJS 添加到 Angular 2 项目中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38278853/
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-10-21 03:38:22  来源:igfitidea点击:

How to add SockJS into Angular 2 project?

typescriptangularsystemjsangular-cliangular2-cli

提问by janetsmith

I use angular-cli to generate a new project. Now I want to add socketJs to the project, but keep getting errors in browser console:

我使用 angular-cli 生成一个新项目。现在我想将 socketJs 添加到项目中,但在浏览器控制台中不断出现错误:

GET http://localhost:4200/url-parse 404 (Not Found)
GET http://localhost:4200/inherits 404 (Not Found)
Unhandled Promise rejection: Error: XHR error (404 Not Found) loading http://localhost:4200/url-parse
        at XMLHttpRequest.wrapFn [as _onreadystatechange] (http://localhost:4200/vendor/zone.js/dist/zone.js:769:30)
        at ZoneDelegate.invokeTask (http://localhost:4200/vendor/zone.js/dist/zone.js:356:38)
        at Zone.runTask (http://localhost:4200/vendor/zone.js/dist/zone.js:256:48)
        at XMLHttpRequest.ZoneTask.invoke (http://localhost:4200/vendor/zone.js/dist/zone.js:423:34)
    Error loading http://localhost:4200/url-parse as "url-parse" from http://localhost:4200/vendor/sockjs-client/lib/main.js ; Zone: <root> ; Task: Promise.then ; Value: Error: Error: XHR error (404 Not Found) loading http://localhost:4200/url-parse(…)
Error: Uncaught (in promise): Error: Error: XHR error (404 Not Found) loading http://localhost:4200/url-parse(…)
GET http://localhost:4200/json3 404 (Not Found)
GET http://localhost:4200/debug 404 (Not Found)
GET http://localhost:4200/events 404 (Not Found)
GET http://localhost:4200/eventsource 404 (Not Found)
GET http://localhost:4200/crypto 404 (Not Found)
GET http://localhost:4200/json3 404 (Not Found)
GET http://localhost:4200/url-parse 404 (Not Found)
GET http://localhost:4200/debug 404 (Not Found)
GET http://localhost:4200/inherits 404 (Not Found)
Assertion failed: loading or loaded
GET http://localhost:4200/events 404 (Not Found)
Assertion failed: loading or loaded
GET http://localhost:4200/faye-websocket 404 (Not Found)
Assertion failed: loading or loaded
GET http://localhost:4200/eventsource 404 (Not Found)
Assertion failed: loading or loaded
GET http://localhost:4200/http 404 (Not Found)
GET http://localhost:4200/https 404 (Not Found)

This is my steps and configuration:

这是我的步骤和配置:

typings install sockjs-client --save --ambient

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|js.map)',
      'es6-shim/es6-shim.js',
      'reflect-metadata/**/*.+(ts|js|js.map)',
      'rxjs/**/*.+(js|js.map)',
      '@angular/**/*.+(js|js.map)',
      'sockjs-client/**/*.+(js)'
    ]
  });
};

system-config.ts

系统配置文件

/** Map relative paths to URLs. */
const map: any = {
  'sockjs-client': 'vendor/sockjs-client/lib/entry.js'
};

/** User packages configuration. */
const packages: any = {
  'vendor/sockjs-client/lib': {
    'format': 'cjs',
    'defaultExtension': 'js'
  }
};

My custom service class:

我的定制服务类:

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

import * as SockJS from 'sockjs-client';
import BaseEvent = __SockJSClient.BaseEvent;
import SockJSClass = __SockJSClient.SockJSClass;

@Injectable()
export class WebsocketService {

  private sockJs: SockJSClass;

  constructor() {
    console.log('constuctor');
    this.sockJs = new SockJS('/hello');
  }
}

Please let me know how to fix it, thanks a lot!

请告诉我如何解决它,非常感谢!

I can, however, eliminate some error by including the missing lib by adding them one by one in system-config.ts. But I doubt this is the right approach.

但是,我可以通过在 system-config.ts 中一一添加缺失的 lib 来消除一些错误。但我怀疑这是正确的方法。

const map: any = {
  'sockjs-client': 'vendor/sockjs-client/lib/entry.js',
  'json3': 'vendor/sockjs-client/node_modules/json3/lib/json3.js',
  'url-parse': 'vendor/sockjs-client/node_modules/url-parse/index.js',
  'inherits': 'vendor/sockjs-client/node_modules/inherits/inherits.js',
  'debug': 'vendor/sockjs-client/node_modules/debug/debug.js',
  ...
};

回答by Devsullo

In new version of angular2 CLI https://cli.angular.io/it is simple to add library.

在 angular2 CLI https://cli.angular.io/ 的新版本中,添加库很简单。

If you want to add only sockjs_client

如果你只想添加 sockjs_client

1) npm i --save sockjs-client

1) npm i --save sockjs-client

2) In typings.d.tsadd this declaration declare module 'sockjs-client';

2)在typings.d.ts中添加这个声明declare module 'sockjs-client';

But I would recommendto use STOMP-Over-WebSocket Service for angular 2

但我建议将 STOMP-Over-WebSocket 服务用于 angular 2

Install this npm packages

安装这个 npm 包

npm i --save stompjs
npm i --save sockjs-client
npm i --save ng2-stomp-service

In typings.d.ts

typings.d.ts

Add stompjsand sockjs-clientmodule declaration

添加stompjssockjs-client模块声明

declare module 'stompjs';
declare module 'sockjs-client';

In app.module.ts

app.module.ts

import { StompService } from 'ng2-stomp-service';

@NgModule({
  ...
  providers: [StompService]
})

In app.components.ts

app.components.ts

import { StompService } from 'ng2-stomp-service';

private wsConf = {
  host:'test.com'
}

constructor(stomp: StompService) {

  stomp.configure(this.wsConf);

  stomp.startConnect().then(() => {
    console.log('connected');
  });


}

source https://github.com/devsullo/ng2-STOMP-Over-WebSocket

https://github.com/devsullo/ng2-STOMP-Over-WebSocket

回答by Daniel Stradowski

I found a solution to this problem.

我找到了解决这个问题的方法。

The issue is that: npm install sockjs-clientdownloads sockjs-node instead of client. I hope they will fix it soon.

问题是:npm install sockjs-client下载 sockjs-node 而不是客户端。我希望他们能尽快修复它。

In your project you're pointing to vendor/sockjs-client/lib/entry.jsinstead you should download this file http://cdn.jsdelivr.net/sockjs/1/sockjs.min.jsput it in your project and point to it in system-config.ts.

在你指向的项目中,vendor/sockjs-client/lib/entry.js你应该下载这个文件,http://cdn.jsdelivr.net/sockjs/1/sockjs.min.js把它放在你的项目中并指向它system-config.ts

回答by elixiao

In Angular2, the easiest way to import sockjs is to use:

在 Angular2 中,导入 sockjs 最简单的方法是使用:

import 'your_path/sockjs-1.1.1.js'

but before you import, please modify part of the code in first line of 'sockjs-1.1.1.js'.

但是在导入之前,请修改'sockjs-1.1.1.js'第一行的部分代码。

if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.SockJS=e()}

replace the code above to:

将上面的代码替换为:

window.SockJS = e()

after then SockJScould be access from anywhere because now it's a property of window in browser.Also you need to tell typescript SockJS is an ambient variable by adding:

之后SockJS可以从任何地方访问,因为现在它是浏览器中窗口的属性。此外,您需要通过添加以下内容来告诉打字稿 SockJS 是一个环境变量:

declare let SockJS: any