我正在尝试在Angular / Node应用程序中学习socket.io。
我会在角度边发出一个事件,然后在后端听它。
在我的组件文件中:
devtoolset-3
Angular中的Emit事件设置为import { MatTableDataSource } from '@angular/material';
import { AjouttextService } from '../ajouttext.service';
import { DataSource } from "@angular/cdk/collections";
import { Observable } from "rxjs/Observable";
import { nomchamp } from '../model';
import * as io from "socket.io-client";
@Component({
selector: 'app-datatable',
templateUrl: './datatable.component.html',
styleUrls: ['./datatable.component.css']
})
export class DatatableComponent implements OnInit {
constructor(private dataService: AjouttextService) { }
data = [];
url = 'http://localhost:8080';
private socket = io.connect(this.url);
displayedColumns = ['text'];
dataSource = new UserDataSource(this.dataService);
;
applyFilter(filterValue: string) {
filterValue = filterValue.trim(); // Remove whitespace
filterValue = filterValue.toLowerCase(); // MatTableDataSource defaults to lowercase matches
}
ngOnInit() {
this.socket.emit('save-message', { room: "hello" });
}
}
所以它应该在所有情况下发出一个事件,我的组件由app.component调用。
然后在服务器方面,我会打印一个console.log OnInit
on
事件
'save-message'
当我运行服务器时,只有连接事件正在运行。我得到“用户在我的控制台中连接但没有”用户保存的消息“
我的期望是什么?
在客户端运行app(DatatableComponent组件)
时在服务器控制台上打印var http = require("http");
var admin = require('firebase-admin');
var firebase = require("firebase");
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var port = process.env.app_port || 8080; // set our port
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
var server = app.listen(port);
var io = require("socket.io")(server);
var routerProj = require("./routes/routes");
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT ,DELETE');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept,*");
next();
});
var config = {
...Config...
};
firebase.initializeApp(config);
var serviceAccount = require("./ServiceAcountKey.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://datatable-18f93.firebaseio.com"
});
app.use("/v1", routerProj, function (req) {
//Create HTTP server and listen on port 8000 for requests
});
// Print URL for accessing server
console.log("Server running at http://127.0.0.1:8080/");
io.on("connection", function (socket) {
console.log("user connected !");
});
io.on('save-message', function (socket) {
console.log("user saved message");
});
答案 0 :(得分:2)
尝试将服务器端代码修改为:
io.on('connection', function (socket) {
console.log('user connected !');
socket.on('save-message', function (socket) {
console.log('user saved message');
});
});
在socket
对象上注册消息侦听器,而不是在初始连接时收到的io
。