Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/367.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 当socket.io向';登录';,TypeError:无法读取属性';导航';未定义的_Javascript_Angular_Typescript - Fatal编程技术网

Javascript 当socket.io向';登录';,TypeError:无法读取属性';导航';未定义的

Javascript 当socket.io向';登录';,TypeError:无法读取属性';导航';未定义的,javascript,angular,typescript,Javascript,Angular,Typescript,我正在使用angular 4和socket.io开发聊天应用程序。 这是我的代码 export class UserService { socket; // determines if a user is logged in or not loggedIn: ''; constructor(private router: Router) { this.socket = io('http://localhost:8890'); this.socket.on('login',

我正在使用angular 4和socket.io开发聊天应用程序。
这是我的代码

export class UserService {
socket;


// determines if a user is logged in or not
loggedIn: '';

constructor(private router: Router) {
    this.socket = io('http://localhost:8890');
    this.socket.on('login', function (result) {
        if (result) {
            this.loggedIn = true;
            this.router.navigate(['/profile']);
        } else {
            this.loggedIn = false;
        }
        localStorage.setItem('loggedIn', this.loggedIn);
        console.log(result);
    });
}}
因此,每当socket.io发送到“login”时,我就会在控制台上收到此错误
错误类型错误:无法读取未定义的属性“navigate”
我更改了代码并从构造函数中初始化了
路由器

export class UserService {
socket;


// determines if a user is logged in or not
loggedIn: '';
router: Router;

constructor() {
    this.socket = io('http://localhost:8890');
    this.socket.on('login', function (result) {
        if (result) {
            this.loggedIn = true;
            this.router.navigate(['/profile']);
        } else {
            this.loggedIn = false;
        }
        localStorage.setItem('loggedIn', this.loggedIn);
        console.log(result);
    });
}}
我仍然会犯同样的错误。

如何访问
路由器
,以便在
结果
为真时重定向到另一页?

您正在丢失
变量的上下文,这就是
此.router
未定义的原因。使用箭头语法保留上下文:

this.socket.on('login', (result) => { // <--- here
    if (result) {
        this.loggedIn = true;
        this.router.navigate(['/profile']);
    } else {
        this.loggedIn = false;
    }
    localStorage.setItem('loggedIn', this.loggedIn);
    console.log(result);
});

this.socket.on('login',(result)=>{//我能知道为什么不使用箭头语法就丢失了
router
变量的上下文吗?这就是箭头函数的全部内容。箭头函数维护“outerscope”的词法范围虽然使用
function
关键字的匿名或命名函数创建了一个新的词法作用域。这就是为什么
const
let
对ES6如此重要的原因,它们尊重“块”作用域(
{}
)然而,
var
只考虑了
函数的作用域。这里接受的答案很好地解释了它的细节-@Brian。但是我们可以使用
bind()
method.Correct?谢谢@RameshRajendran.
this.loggedIn=true;
仍然在socketio函数内部工作。我仍然不太明白@Fenton为什么会这样