角套接字连接失败

时间:2019-03-08 06:19:59

标签: angular sockets

我正在使用socket.io-client@types/socket.io-client。有时套接字会自动断开连接。套接字连接失败时,我需要重试代码。

这是我的示例代码。

import { Injectable } from '@angular/core';
import { StorageService } from '@app/services';
import { ToastrService } from 'ngx-toastr';
import { BehaviorSubject, Observable } from 'rxjs';
import * as io from 'socket.io-client';

import { WSUrl } from './../app.constants';

@Injectable({
  providedIn: 'root'
})
export class ChatService {
  private url = WSUrl;
  private socket;

  constructor(private toastr: ToastrService, private storage: StorageService) {
    // Get access token from local storage
    const token = this.storage.getItem<string>('token');

    // For socket connection
    this.socket = io(this.url, {
      query: 'token=' + token
    });

    // Socket connection successfully made
    this.socket.on('connect', () => {
      console.log('Connection Made.');
      this.socket.emit(
        'join',
        {
          login_token: token
        },
        data => {
          console.log('join', data);
          if (data.code === 400) {
            this.toastr.error('Something went wrong.');
            return false;
          }
        }
      );
    });
  }
}

请帮助我。谢谢你。

0 个答案:

没有答案