【发布时间】:2017-05-28 22:16:31
【问题描述】:
所以我已阅读,但没有找到解决问题的方法。 我的问题正如我的标题所问的那样。
这是我的问题,我创建了 2 个组件(NavbarComponent 和 HomepageComponent)。 NarbarComponent 嵌套在 AppComponent 中并处理身份验证,而 HomepageComponent 是 启用路由 组件和应用程序的默认页面。
我想要做的是能够使用像 Auth0 这样的身份验证服务通过单击导航栏中的登录按钮 (NavbarComponent) 来对用户进行身份验证,然后在主页 (HomepageComponent) 上呈现他/她的个人资料。反之亦然,当我单击注销按钮时,用户的个人资料内容应该被删除。
我尝试配置一些架构,但无济于事。首先,我尝试使用共享服务将 NavbarComponent 转换为 HomepageComponent,但它只在页面重新加载时更新 HomepageComponent。
我尝试在 AppComponent 和 NavbarComponent 之间使用共享服务,然后使用 @Input() 从 Parent 到 Child、HomepageComponent 进行传输。
然后我在 AppComponent 和 HomepageComponent 之间运行共享服务时尝试了从 NavbarComponent 到 AppComponent 的 @Output() 和 EventEmitter。
任何信息或见解将不胜感激!
更新
主页组件
import { Component, OnInit } from '@angular/core'
import { Authenticated } from '../definitions/authenticated'
import { AuthCheckService } from '../shared/auth-check.service'
@Component({
selector: 'afn-homepage',
templateUrl: './homepage.component.html'
})
export class HomepageComponent implements OnInit{
private authenticated: Authenticated;
isAuthenticated: boolean;
profile: any;
constructor(public authCheckService: AuthCheckService) { }
ngOnInit() {
this.authCheckService.getAuthenticated().subscribe(authenticated => {
console.log('Receiving auth info in home component from navbar component');
this.authenticated = authenticated;
this.isAuthenticated = this.authenticated.isAuthenticated;
this.profile = this.authenticated.profile;
});
}
}
我尝试制作plunker here。我无法加载它,但它确实包含大部分代码和 AuthService 的模拟。
【问题讨论】:
-
共享服务应该是首选。你能用你尝试过的方法创建一个 plnkr,让人们看到你错过了什么吗?
-
@HarryNinh 根据您的要求添加了 plnkr。我想我在添加 AuthService 时错过了一些东西,因为它不再加载。
-
也许是个愚蠢的问题,但你为什么不为此使用不同的路由,而不是将所有不同的状态压缩到一个组件中,然后使用 Guards 处理身份验证并重新路由用户?跨度>
标签: angular router auth0 sharedservices