Angular 角4调用函数内部服务
我有Angular 角4调用函数内部服务,angular,socket.io,Angular,Socket.io,我有chat.service.ts文件。在这个文件中,我有一些函数。但是我想在构造函数中调用一个函数,但是我得到了一个错误类型ERROR:this.join不是一个函数。我需要帮助如何调用服务内部的函数 以下是我的示例代码: import { Injectable } from '@angular/core'; import * as io from 'socket.io-client'; import { Observable } from 'rxjs'; @Injectable({ p
chat.service.ts
文件。在这个文件中,我有一些函数。但是我想在构造函数中调用一个函数,但是我得到了一个错误类型ERROR:this.join不是一个函数
。我需要帮助如何调用服务内部的函数
以下是我的示例代码:
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);
});
});
}
}
尝试使用箭头语法
=>
将此
的上下文保留到套接字处理程序/回调中的类:
this.socket.on('connect', () => {
console.log("Connection Made.");
this.join();
});
希望这有帮助