Создание веб-сокета с помощью sockjs-client/sockjs в проекте angular2 webapp
Я использую проект веб-приложения Angular2 для FRONT-END и Vertex3 для BACK-END.
Используя Sockjs-клиент, я создаю websocket (на стороне клиента) для создания канала связи между Frontend и Backend.
Я установил sockjs-клиент, используя npm:
npm установить sockjs-клиент
Когда я импортирую sockjs-клиент в файл LoginService.ts:
импортировать * как SockJS из 'sockjs-client';
export class LoginService {
URL: string = 'http://localhost:8082/eventbus';
sock: SockJS;
handlers = {};
private _opened: boolean = false;
public open(): void {
if (!this._opened) {
this.sock = new SockJS(this.URL);
this.sock.onopen = (e) => {
this.callHandlers('open', e);
}
this.sock.onmessage = (e) => {
this.messageReceived(e);
}
this.sock.onclose = (e) => {
this.callHandlers('close', e);
}
this._opened = true;
}
public isOpen(): boolean {
return this._opened;
}
public close(): void {
if (this._opened) {
this.sock.close();
delete this.sock;
this._opened = false;
}
}
private messageReceived (e) {
var msg = JSON.parse(e.data);
this.callHandlers('message', msg.type, msg.originator, msg.data);
}
private callHandlers (type: string, ...params: any[]) {
if (this.handlers[type]) {
this.handlers[type].forEach(function(cb) {
cb.apply(cb, params);
});
}
}
public send (type: string, data: any) {
if (this._opened) {
var msg = JSON.stringify({
type: type,
data: data
});
this.sock.send(msg);
}
}
}
нет ошибок при запуске проекта angular2 webapp с помощью
сервер запуска npm
Но на стороне клиента не создается соединение через веб-сокет. Как я уже создал сервер с использованием вершины vertex.createHttpServer
(который размещен на: http://localhost:8082/).
Итак, у меня есть две проблемы:
1.Не удается импортировать sockjs-клиент в веб-приложение angular2, поэтому невозможно создать соединение через веб-сокет.
2. Ошибка при создании проекта веб-приложения angular2 как sockjs-client не найдена в node_modules (странно, что он присутствует в node_modules)
Я что-то пропустил?
Заранее спасибо!!!
1 ответ
Нашел способ интегрировать sockjs в angular2 без использования typings
,
Используйте следующие шаги:
- Импортировать
sockjs-event.js
а такжеsockjs-client.js
вindex.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>MyApp</title>
<script src="/sockjs-client.js"></script>
<script src="/sockjs-event.js"> </script>
......
</head>
<body>
<my-app>Loading...</my-app>
</body>
</html>
- Создать сервис экспорта
myapp.service.ts
declare var EventBus: any;
@Injectable()
export class ConsoleService {
URL: string = 'http://localhost:8082/eventbus';
handlers = {};
eventBus: any;
private _opened: boolean = false;
public open(): void {
if (!this._opened) {
this.eventBus = new EventBus(this.URL);
this.eventBus.onopen = (e) => {
this._opened = true;
console.log("open connection");
this.callHandlers('open', e);
this.eventBus.publish("http://localhost:8082", "USER LOGIN INFO");
this.eventBus.registerHandler("http://localhost:8081/pushNotification", function (error, message) {
console.log(message.body);
//$("<div title='Basic dialog'>Test message</div>").dialog();
});
}
this.eventBus.onclose = (e) => {
this.callHandlers('close', e);
}
}
}
public isOpen(): boolean {
return this._opened;
}
public close(): void {
if (this._opened) {
this.eventBus.close();
delete this.eventBus;
this._opened = false;
}
}
.......
public send (type: string, data: any) {
if (this._opened) {
var msg = JSON.stringify({
type: type,
data: data
});
this.eventBus.publish("http://localhost:8082",msg);
}
}
};
export default ConsoleService;
- Перейти к вашему стартовому модулю, в моем случае это
app.module.ts
и загрузить свой сервисmyapp.service.ts
в угловой начальной загрузке
import { AppComponent } from './app.component';
....
import { ConsoleService } from 'services/myapp.service';
@NgModule({
imports: [
....
],
providers: [ ConsoleService ],
declarations: [
AppComponent,
...
],
bootstrap: [AppComponent]
})
4. Откройте открытый веб-сокет из вашего начального компонента.
app.component.ts
import { Component } from '@angular/core';
import 'style/app.scss';
import { ConsoleService } from 'services/globalConsole.service';
@Component({
selector: 'my-app', // <my-app></my-app>
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
constructor (private consoleService: ConsoleService) {
consoleService.onOpen((e) => {
consoleService.send('message', "xyz");
});
consoleService.open();
}
}
- Наконец вы можете использовать
EventBus
вpublish
а такжеregisterHandler
в любой.ts
файл с использованием импортаConsoleService
,
Я надеюсь, это поможет:)