客户端使用Angular 6,服务器端使用node.js。
在angular 6控制台中,它打印消息并
socket.io id({message: "Hello World", id: "6An-ctwlwbZZWrfMAAAB"})
使用下面的代码后。
此代码正确或此代码中的任何更改bcoz我不确定此代码是否有助于正确纠正此问题。
另一个查询是我的项目中有15个以上的组件,因此如何将该socket.io
用于所有组件,或者必须将此app.component.ts
代码导入所有其他组件。
app.js(服务器端)
after installing (npm i socket.io)
const express = require('express');
var app = express();
const http = require('http');
const socketIo = require('socket.io');
const server = http.Server(app);
const io = socketIo(server);
server.listen(3000,function(req,res){
console.log("listen at 3000!");
});
io.on('connection',(socket) => {
socket.emit('hello',{
message : 'Hello World',id: socket.id
})
});
app.component.ts(客户端)
after installing (npm i socket.io)
import * as socketIo from 'socket.io-client';
export class AppComponent implements OnInit {
ngOnInit(){
const socket = socketIo('http://localhost:3000/');
socket.on('hello',(data) => console.log(data));
}
}
}
答案 0 :(得分:3)
实现此机制的一种方法是使用ngx-socket-io
,将节点服务器连接到我已经实现的模块级别或根级别,如下所示
app.module.ts代码
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { SocketIoModule, SocketIoConfig } from 'ngx-socket-io';
import { AppComponent } from './app.component';
const config: SocketIoConfig = { url: 'http://192.168.1.187:9301', options: {} };
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
SocketIoModule.forRoot(config),
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
创建一项服务来处理您的传入和传出流量。
import { Injectable } from '@angular/core';
import { Socket } from 'ngx-socket-io';
@Injectable({
providedIn: 'root'
})
export class SocketService {
constructor(public socket: Socket) { }
getMessage() {
return this.socket
.fromEvent<any>('msg')
.map(data => data.msg);
}
sendMessage(msg: string) {
this.socket.emit('msg', msg);
}
}
更新您组件文件中的代码
export class AppComponent implements OnInit {
constructor(private socketService: SocketService) {}
title = 'app';
incomingmsg = [];
msg = 'First Protocol';
ngOnInit() {
this.socketService
.getMessage()
.subscribe(msg => {
console.log('Incoming msg', msg);
});
this.sendMsg(this.msg);
}
sendMsg(msg) {
console.log('sdsd', msg);
this.socketService.sendMessage(msg);
}
}
答案 1 :(得分:1)
您可以创建用于使用套接字的服务。例如(当然,这是一个非常简单的示例):
/* e.g app/shared/io/io.service.ts */
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import * as socketIo from 'socket.io-client';
const SERVER_URL = '/';
/** Your events enum */
export enum IOEventName {
EVENT_NAME_1 = "EVENT_NAME_1",
EVENT_NAME_2 = "EVENT_NAME_2",
...
}
/** Interfaces for your event messages */
export interface IEventName1Message {
propOne: number,
propTwo: string,
...
}
export interface IEventName2Message {
propOne: Date,
propTwo: Boolean,
...
}
...
@Injectable()
export class SocketService {
private socket: SocketIOClient.Socket;
public initSocket(): void {
this.socket = socketIo(SERVER_URL);
}
public onEvent<T>(event: IOEventName): Observable<T | Array<T>> {
return new Observable<T>(observer => {
this.socket.on(event, (data: T) => observer.next(data));
});
}
public destroy() {
if (this.socket) {
this.socket.removeAllListeners();
this.socket.close();
this.socket = undefined;
}
}
}
并在任何组件中使用它:
import { SocketService, IOEventName, IEventName1Message, IEventName2Message }
from 'app/shared/io/io.service';
export class AppComponent implements OnInit, OnDestroy {
constructor(private socketService: SocketService) { }
ngOnInit() {
this.socketService.initSocket();
this.socketService
.onEvent<IEventName1Message>(IOEventName.EVENT_NAME_1)
.subscribe(data => { /* message received */ });
this.socketService
.onEvent<IEventName2Message>(IOEventName.EVENT_NAME_2)
.subscribe(data => { /* message received */ });
}
ngOnDestroy() {
this.socketService.destroy();
}
}
答案 2 :(得分:1)
创建服务并将套接字数据转换为可观察流
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/behaviorSubject';
import {Observer} from 'rxjs/Observer';
import { Observable } from 'rxjs/Observable';
import * as Rx from 'rxjs';
import * as io from 'socket.io-client';
@Injectable()
export class ChatService {
observable:Observable<string>;
socket;
constructor() {
this.socket=io('http://localhost:3000');
}
getData():Observable<string>{
return this.observable=new Observable((observer)=>{
this.socket.on('hello',(data)=>observer.next(data)
);})
}
//This one is for send data from angular to node
pushData(e){
this.socket.emit('hello',e);
}
}
然后从组件调用
App.component.ts
import { Component } from '@angular/core';
import { ChatService } from './common/chat.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title;
chat;
constructor(private cService:ChatService){
this.cService.getData().subscribe(data=>console.log(data));
}
onClick(e:string){
this.cService.pushData(e);
this.chat='';
}
}