行为主体在离子4

时间:2019-03-29 09:59:55

标签: angular typescript ionic-framework rxjs behaviorsubject

我有一个简单的服务,叫做套接字服务

import { Injectable } from '@angular/core';
import { Socket } from 'ngx-socket-io';
import { AuthenticationService } from './authentication.service';
import { BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class SocketsService {

  isConnected = false;
  isOnline = new BehaviorSubject(false);

  constructor(private socket: Socket,private authenticationService : AuthenticationService) {
   }

   connect(){
     console.log("connecting to socket server....")
    return new Promise((resolve, reject) => {
    if(!this.isConnected)
    {
      this.socket.connect();
      console.log("Authenticating socket server....")
      this.socket.emit('authentication', {"HESOYAM" : this.authenticationService.user, "AEZAKMI" : this.authenticationService.pass, 'type' : 'mobile-app' });
      this.isConnected=true;

      this.socket.on("authenticated",function(data){
        console.log("socket auth was succesful with data "+data);
        console.log(this.isOnline);
        //this.isOnline.next(true);
      })
    }
   })
  }

执行this.isOnline.next(true);时,返回的isOnline错误未定义。 控制台日志this.isOnline类似地打印在控制台中未定义。 我正在从页面

调用connect方法
export class TabsPage implements OnInit {

  constructor(private socketService : SocketsService, private authenticationService : AuthenticationService) { }

  ngOnInit() {
    this.authenticationService.refershToken().then(()=>{
      this.socketService.connect()
    })    
  }

}

刷新令牌的定义如下

refershToken(){    
return new Promise((resolve, reject) => {
 this.storage.get(user).then((user) => {
  this.storage.get(pass).then((pass) => {
    if(user && pass){
      console.log("refresing token")
      this.login(user,pass).subscribe((res: LoginInterface) => {      
        if(res.auth == true){
         this.save_login(user,pass,res.name,res.token)
         this.user = user
         this.pass = pass         
         resolve()    
        }else{
          throw new Error('Auth Failed');
        }
      })
    }   
  });
});

})   }

我想我缺少了一些非常基本的东西。

PS:我是Typescript和Angular的新手

1 个答案:

答案 0 :(得分:1)

this对象在您的SocketsService中在此行丢失:

this.socket.on("authenticated",function(data){ } 

请将函数更改为这样的lambda表达式

this.socket.on("authenticated", data =>{ })

为什么,请参考https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions