【发布时间】: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);
});
});
}
}
【问题讨论】: