我可以在angular4中使用套接字。我想当用户登录时,服务器将用户发送到客户端,但我可以在客户端获取用户。这是我的代码:
套接字服务
@Injectable()
export class SocketService {
private socket;
private url : string = 'http://localhost:2912';
constructor() {
}
init(){
console.log('runnig')
this.socket = io(this.url)
this.socket.on('user',(user)=>{
console.log('init',user) //I cant log user in here
})
}
getListUser(){
let observable = new Observable(observer=>{
this.socket.on('user',(user)=>{
console.log(user) // cant log user in here
observer.next(user)
})
})
return observable
}
}
App.module
providers: [
SocketService,
{
provide: APP_INITIALIZER,
useFactory: (sk: SocketService) => function() {return sk.init()},
deps: [SocketService],
multi: true
}],
请解释一下为什么我可以在init函数中登录用户但不能在getListUser函数中登录。我哪里错了?非常感谢