【问题标题】:Angular 4 call function inside service服务内的Angular 4调用函数
【发布时间】:2019-01-05 05:54:04
【问题描述】:

我有chat.service.ts 文件。在这个文件中,我有一些功能。但是我想在构造函数中调用一个函数,但我得到了一个ERROR TypeError: this.join is not a function。我需要帮助如何在服务中调用函数。

这是我的示例代码:

import { Injectable } from '@angular/core';
import * as io from 'socket.io-client';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ChatService {
  private url = 'http://localhost:5000/';
  private socket;

  constructor() {
    this.socket = io(this.url, {
      "query": "token=XXXX"
    });

    this.socket.on('connect', function () {
      console.log("Connection Made.");
      this.join();
    });
  }

  public join(): void {
    this.socket.emit('join', {
      "login_token": "XXXX"
    });
  }

  public sendMessage(message) {
    this.socket.emit('message', message);
  }

  public getMessages = () => {
    return Observable.create((observer) => {
      this.socket.on('new-message', (message) => {
        observer.next(message);
      });
    });
  }
}

【问题讨论】:

    标签: angular socket.io


    【解决方案1】:

    尝试使用箭头语法=> 来将this 的上下文保留到套接字处理程序/回调中的类:

    this.socket.on('connect', () => {
      console.log("Connection Made.");
      this.join();
    });
    

    希望对您有所帮助!

    【讨论】:

      猜你喜欢
      • 2018-03-23
      • 1970-01-01
      • 1970-01-01
      • 2018-11-14
      • 2017-02-08
      • 2018-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多