角度6:从其他组件调用后,服务中的变量未定义

时间:2018-09-21 12:56:56

标签: angular typescript service components undefined

我有2个组件登录和Messenger组件,以及1个称为聊天服务的服务,该组件位于登录组件中。

现在的问题是,当我从登录组件调用chatservice并设置套接字变量的值时,它将更新该变量。但是当我从Messenger组件调用聊天服务的另一种方法(recievetextMessage())之后,套接字变量的值未定义。代码如下。

聊天服务

import { Injectable } from "@angular/core";

import * as io from 'socket.io-client';

import { Observable } from 'rxjs/Observable';


Injectable();

export class chatservice {


socket:any;  // the variable that i am updating
test :any;
constructor() {

}

socketId = () => {

    this.socket = io(''); //updating of variable from login component is here
    console.log(this.socket);
    let observable = new Observable<{ id: any }>(observer => {
        this.socket.on('socketId', (data) => {
            observer.next(data);
        });
        return () => { this.socket.disconnect(); }
    });

    return observable;
}

sendtextmessage(data) {
    this.socket.emit('sendtextMessage', data);
}

recievetextMessage = () => { // called from messenger component
    console.log(this.socket); // gives undefined
    console.log(this.test);
    let observable = new Observable(observer => {
        console.log(this.test);
        console.log(this.socket);
        this.socket.on('recievetextMessage', (data) => {
            console.log(data);
            observer.next(data);
        });
        return () => { this.socket.disconnect(); }
    });

    return observable;
}
}

0 个答案:

没有答案