2016-09-25 40 views
1

嗨,我已经设置了这个plunkr来演示我的问题。 https://plnkr.co/edit/tO4xbD15A3FvjpaGw6J5?p=previewAngular2组件在通过回调路由器重定向后没有类引用

这是成功登录后执行重定向的代码的主要部分。我不是指“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]); 
}); 
} 

的例子使用文件“应用程序/ authentication.ts”我已经把两个版本: “app/authentication.ts.works”和一个 “app/authentication.ts.worksNot”

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

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

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

任何帮助表示赞赏。

赫尔穆特·

回答

0

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

改用箭头功能() =>它保留的this范围:

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

您的代码有function()多种用途。我建议你全部替换它们,除非打算使用function()的行为(罕见情况)。

+0

谢谢。没有太大的区别......但会考虑它并做出改变。 –

0

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

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