可以使用socket.io LARAVEL和IONIC 3制作一个api吗?

时间:2018-07-17 14:53:54

标签: php angular laravel sockets ionic-framework

我正在使用Ionic 3使用socket.ionpm server做一些教程,我想消耗Laravel php api,这样做,有可能吗? / p>

此应用程序运行正常,我的疑问是如果可以使用Laravel API

来实现这些方法

基本上我想做的是:将请求ionic发布到API LARAVEL,然后返回观察员或类似的东西。

对于英语不好,我很抱歉:(

Chat-Room.ts

import { Component } from '@angular/core';
import { NavController, IonicPage, NavParams, ToastController } from 'ionic-angular';
import { Socket } from 'ng-socket-io';
import { Observable } from 'rxjs/Observable';
 ...


  sendMessage() {
    this.socket.emit('add-message', { text: this.message });
    this.message = '';
  }

  getMessages() {
    let observable = new Observable(observer => {
      this.socket.on('message', (data) => {
        observer.next(data);
      });
    })
    return observable;
  }

  getUsers() {
    let observable = new Observable(observer => {
      this.socket.on('users-changed', (data) => {
        observer.next(data);
      });
    });
    return observable;
  }

  ionViewWillLeave() {
    this.socket.disconnect();
  }

}

App.module.ts

import { SocketIoModule, SocketIoConfig } from 'ng-socket-io';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { ChatRoomPage } from '../pages/chat-room/chat-room';
const config: SocketIoConfig = { url: 'http://localhost:3001', options: {} };
...
  imports: [
    BrowserModule,
    SocketIoModule.forRoot(config),
    IonicModule.forRoot(MyApp)
  ],
...

聊天服务

let app = require('express')();
let http = require('http').Server(app);
let io = require('socket.io')(http);

io.on('connection', (socket) => {

  socket.on('disconnect', function(){
    io.emit('users-changed', {user: socket.nickname, event: 'left'});   
  });

  socket.on('set-nickname', (nickname) => {
    socket.nickname = nickname;
    io.emit('users-changed', {user: nickname, event: 'joined'});    
  });

  socket.on('add-message', (message) => {
    io.emit('message', {text: message.text, from: socket.nickname, created: new Date()});    
  });
});

var port = process.env.PORT || 3001;

http.listen(port, function(){
   console.log('listening in http://localhost:' + port);
});

0 个答案:

没有答案