我试图使用socket io连接到角度2与最新的发布包, 我从angular2 / quickstart-master
下载它我已将此脚本放在index.html
上<script src="socket.io/socket.io.js"></script>
然后即时创建服务器,
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var app = express();
var http = require('http');
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(8000);
io.set("origins", "*:*");
var currentPrice = 99;
io.on('connection', function (socket) {
socket.emit('priceUpdate',currentPrice);
socket.on('bid', function (data) {
currentPrice = parseInt(data);
socket.emit('priceUpdate',currentPrice);
socket.broadcast.emit('priceUpdate',currentPrice);
});
});
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'app')));
app.use('/', routes);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
module.exports = app;
并将socket io放在组件上,
price: number = 0.0;
socket : any;
bidValue = '';
constructor() {
this.socket = io('http://localhost:8000'); **<< on this part**
this.socket.on('priceUpdate', function(data){
this.price = data;
}.bind(this));
}
bid(){
this.socket.emit('bid', this.bidValue);
this.bidValue = '';
}
但我发现错误,说无法找到io,
我的代码有什么问题吗?
答案 0 :(得分:0)
在导入后添加declare var io:any