繁体   English   中英

从回调重定向到路由器后,Angular2组件没有类引用

[英]Angular2 component doesn't have class reference after redirect via router from callback

嗨,我已经设置了这个plunkr来证明我的问题。 https://plnkr.co/edit/tO4xbD15A3FvjpaGw6J5?p=preview

这是在成功登录后执行重定向的代码的主要部分。 我不能引用“isLoggedIn”变量,因为这是在回调函数中...

loginLaunch() {
console.log("authentication.ts:loginLaunch()");
let authProperties = AUTH_PROPERTIES; 
authProperties.immediate = false;
// Sign the user in, and then retrieve their ID.
let ga = gapi.auth2.getAuthInstance();
let router = this.router;
let redirect2 = this.redirectUrl;
ga.signIn(authProperties).then(function() {
    console.log("authentication.ts:loginLaunch() - logged on:"+ ga.currentUser.get().getId());
    //this.isLoggedIn=true;
    // Redirect the user
    console.log("authentication.ts:loginLaunch() - logged in now, redirect to "+redirect2);
    router.navigate([redirect2]);
}); 
}

该示例使用文件“app / authentication.ts”,我有两个版本:“app / authentication.ts.works”和“app / authentication.ts.worksNot”

第一个是虚拟身份验证(实际上并不是要求您输入密码),第二个是使用Google身份验证。

我遇到的问题是这个。 使用google身份验证(使用promise / callback),重定向后的Angular2组件没有对组件类的引用。 在这种情况下,它应该在用户登录后显示“标签”的详细信息。但事实并非如此。 你知道这里发生了什么吗?

如果将“app / authentication.ts.works”的内容复制到“app / authentication.ts”中,则应用程序将按预期工作:登录后,标签信息将显示在Component1页面上。

任何帮助表示赞赏。

赫尔穆特

不要使用function ()因为这会导致this指向函数而不是类。

使用代替箭头功能() =>其保留的范围的this

ga.signIn(authProperties).then(() => {

您的代码有几个使用function () 我建议你全部替换它们,除非是在function ()的行为(罕见情况)。

我找出了问题所在(更新了plunkr示例)。 我不得不直接从“authenticate.ts”调用router.navigate,而是使用“zone.run()”来调用它,以确保当前区域在不相关的子组件中获取更改(我的猜测是......) :

    this.zone.run(()=>{
        router.navigate([redirect2])
    });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM