实时:Angular 6 +回送+ loopback-sdk-builder + IO模块

时间:2018-10-05 19:52:13

标签: angular angular6 loopbackjs angular-loopback io-socket

经过几个小时的研究和测试,我终于来寻求帮助……我想与环回建立实时连接。我正在使用Builder SDK https://github.com/mean-expert-official/loopback-sdk-builder/

似乎建造者可以提供几种实时性。包括IO模块和Fireloop。 Fireloop文档离线... http://fireloop.io/

所以我将测试的重点放在了模块IO模块上,但是文档是大概的...

https://github.com/mean-expert-official/loopback-sdk-builder/wiki/9.-IO-Module

所以第一步,我制作一个用于回送的启动脚本 (带有https://loopback.io/doc/en/lb3/Boot-script-generator.html

但是示例中提供的代码不起作用。

module.exports = function (app) {
  app.on('started', function () {
    app.mx.IO.emit('test', 'Hello World');
    app.mx.IO.on('test', function (message) {
      console.log('MESSAGE: ', message);
    });
  });
};

“。mx”在应用程序上不存在。

因此,在进行其他一些搜索之后,我借助https://gist.github.com/frzkhan/e302177285f850cc04010d6b64a06321

找到了一种方法

我修改了server.js

app.start = () => {
  app.server = app.listen(() => {
    app.emit('started')
    const baseUrl = app.get('url').replace(/\/$/, '')

    console.log('Web server listening at: %s', baseUrl)
    if (app.get('loopback-component-explorer')) {
      const explorerPath = app.get('loopback-component-explorer').mountPath

      console.log('Browse your REST API at %s%s', baseUrl, explorerPath)
    }
  })

  return app.server
}

然后在我的启动脚本中:

'use strict';
const SocketIo = require('socket.io')

module.exports = function(app) {    
  app.on('started', function () {
    app.io = SocketIo(app.server)

    app.io.on('connection', socket => {
      console.log('a user connected')
      app.io.emit('test', 'Hello World');

      app.io.on('test', (socket) => {
        console.log("This log is never displayed on server side !");
        app.io.emit('test', 'Reply Hello World');
      })

      socket.on('disconnect', () => {
        console.log('user disconnected')

      })
    })
  });


};

在我的组件中:

  constructor(private realTime: RealTime){
    LoopBackConfig.setBaseURL('http://127.0.0.1:3000');
    LoopBackConfig.setApiVersion('api');

    this.realTime.onReady().subscribe(() => {
      this.realTime.IO.emit('test', 'This is a message emit from client');
      this.realTime.IO.on('test').subscribe((msg: any) => console.log('This is a message emit from the server  =' + msg), (err: any) => console.log(err));
    });
} 

结果是我从服务器收到消息 客户端控制台:

socket.connections.ts:74使用以下内容创建新的连接:http://127.0.0.1:3000 real.time.ts:103实时连接已建立 admin-category.component.ts:72这是从服务器= Hello World

发出的消息

但是在我的服务器端控制台中:

a user connected

我还添加了一个按钮来发出消息:

 emitMessage() {
    console.log(this.realTime.connection.isConnected());
    this.realTime.onReady().subscribe(() => {
      this.realTime.IO.emit('test', "hey this is my message");
    });
  }

this.realTime.connection.isConnected()的值为true,但在服务器端仍未收到任何信息...

欢迎任何想法或建议! 您使用Angular 6和环回进行实时处理的最佳实践是什么?

谢谢

迈克

0 个答案:

没有答案