angularjs Angular 7和Laravel-Echo

z6psavjg  于 5个月前  发布在  Angular
关注(0)|答案(1)|浏览(51)

所以我试着让后端的laravel和前端的Angular工作。Laravel版本5.8和Angular 7.2我有我的事件

public function broadcastOn()
{
    return new Channel('test');
}

public function broadcastAs() {
    return 'message.sent';
}

字符串
我做了一个路线,

Route::get('/fire', function () {
    event(new \App\Events\Messages\MessageEvent());
    return 'ok';
});


在redis和laravel-echo-server中,

"PUBLISH" "test" "{\"event\":\"message.sent\",\"data\":{\"a\":\"a\",\"socket\":null},\"socket\":null}"
Channel: test
Event: message.sent

的字符串
但是每当我试图从Angular 连接到套接字的时候,有些东西失败了,它既不连接也不抛出错误。套接字的响应形式是200,它每25秒获得200(回声服务器配置),但ws连接没有建立,也没有捕获任何事件
Angular 的侧

import {Component, Injectable, OnInit} from '@angular/core';
import Echo from 'laravel-echo';
@Component({
    moduleId: module.id.toString(),
    templateUrl: 'index.html',
})

@Injectable()
export class MessagesPagesViewComponent {

    echo: any;

    constructor() {

        const SocketIoClient = require('socket.io-client');
        try {
            this.echo = new Echo({
                broadcaster: 'socket.io',
                host: 'localhost:6001',
                client: SocketIoClient,
            });
        } catch (e) {
            console.log(e);
        }
        this.echo.connector.socket.on('connect', () => {
            console.log('CONNECTED');
        });

        this.echo.connector.socket.on('reconnecting', () => {
            console.log('CONNECTING');
        });

        this.echo.connector.socket.on('disconnect', () => {
            console.log('DISCONNECTED');
        });

        this.echo.connector.socket.on('test.message.sent', (data) => {
           console.log('1', data);
        });

        this.echo.connector.socket.on('.message.sent', (data) => {
            console.log('2', data);
        });

        this.echo.connector.socket.on('message.sent', (data) => {
            console.log('3', data);
        });

        this.echo.join('test').joining((data) => {
            console.log('joining', data);
        }).leaving((data) => {
            console.log('leaving', data);
        });

        this.echo.join('test2').joining((data) => {
            console.log('joining', data);
        }).leaving((data) => {
            console.log('leaving', data);
        });

        this.echo.channel('test').listen('.message.sent', (data) => {
            console.log('From laravel echo: ', data);
        });
        this.echo.channel('test2').listen('.message.sent', (data) => {
            console.log('From laravel echo: ', data);
        });


        console.log(this.echo);
    }

}


laravel-echo-server.json

{
    "authHost": "http://localhost",
    "authEndpoint": "/broadcasting/auth",
    "clients": [],
    "database": "redis",
    "databaseConfig": {
        "redis": {
            "host": "172.24.0.2",
            "port": "6379"
        },
        "sqlite": {
            "databasePath": "/database/laravel-echo-server.sqlite"
        }
    },
    "devMode": true,
    "host": null,
    "port": "6001",
    "protocol": "http",
    "socketio": {},
    "secureOptions": 67108864,
    "sslCertPath": "",
    "sslKeyPath": "",
    "sslCertChainPath": "",
    "sslPassphrase": "",
    "subscribers": {
        "http": true,
        "redis": true
    },
    "apiOriginAllow": {
        "allowCors": true,
        "allowOrigin": "*",
        "allowMethods": "GET, POST",
        "allowHeaders": "Origin, Content-Type, X-Auth-Token, X-Requested-With, Accept, Authorization, X-CSRF-TOKEN, X-Socket-Id"
    }
}

nmpmafwu

nmpmafwu1#

我也遇到过同样的问题,但我解决了。
目前Laravel Echo无法与socket.io-client v.4.7建立WebSocket连接。但它可以与socket.io-client版本**^2.5.0**正常工作
package.json

{
  "dependencies": {
    "laravel-echo": "^1.15.3", // latest version as of 29th Nov, 2023
    "socket.io-client": "^2.5.0",
  },
  "devDependencies": {
    "@types/socket.io-client": "^3.0.0",
  }
}

字符串
x1c 0d1x的数据
notification.service.ts

// notification.service.ts
import { Injectable } from '@angular/core';
import Echo from 'laravel-echo';
// import { io } from 'socket.io-client';

@Injectable({
    providedIn: 'root',
})
export class NotificationService {
    private echo!: Echo;

    constructor() {
        this.initEcho();
    }

    private initEcho() {
        const io = require('socket.io-client');
        this.echo = new Echo({
            broadcaster: 'socket.io',
            client: io,
            host: 'http://localhost:6001', // Change this to your Laravel Echo server host
        });

        this.echo.connector.socket.on('connect', () => {
            console.log('%c Connected to WebSocket', 'background: blue; color: white');
        });

        this.echo.connector.socket.on('reconnecting', () => {
            console.log('%c ReConnecting to WebSocket', 'background: yellow; color: green');
        });

        this.echo.connector.socket.on('disconnect', () => {
            console.log('%c Disconnected from WebSocket', 'background: red; color: white');
        });

        this.echo.channel('user-channel').listen('.UserEvent', (data: any) => {
            // Handle the real-time notification data here
            console.log('Notification received:', data);
        });
    }
}


test-notification.component.ts

import { Component, OnInit } from '@angular/core';
import { NotificationService } from './notification.service';

@Component({
  selector: 'app-test-notification',
  templateUrl: './test-notification.component.html',
  styleUrls: ['./test-notification.component.scss']
})
export class TestNotificationComponent implements OnInit {

  constructor(protected notificationService: NotificationService) { }

  ngOnInit(): void {
  }
}

相关问题