angular - 显示访客的注册/登录链接,登录时隐藏?

标签 angular angular-services

我有一个包含 3 个项目的导航栏 registerloginlogout

我正在尝试在用户登录/注销时更新导航栏项目的可见性。

我正在使用通知服务来通知我的 TopNav 组件 更新一个名为 loggedIn 的变量,该变量依次显示/隐藏上面的这些元素

问题是:通知服务没有向 TopNavComponent 发送警报!

我调试了我的代码,有时 loginStatusChanged$ 观察者数组是空的,这是不应该发生的事情,因为我应该订阅通知!


TopNavComponent.ts

import { NotificationService   } from 'app/includes/services/notification.service';
import { AuthenticationService } from 'app/includes/services/auth-services/authentication.service';

@Component({
    selector     : 'app-topnav',

    template     : `
<a [routerLink]="['/register']" *ngIf="!loggedIn">Register</a>
<a [routerLink]="['/login']" *ngIf="!loggedIn">Login</a>
<app-loggedin-menu remove-host *ngIf="loggedIn"></app-loggedin-menu>`,

    providers    : [Auth, NotificationService, AuthenticationService]
})
export class TopNavComponent implements OnInit
{
    subscription   : Subscription;
    loggedIn = this.auth.loggedIn();

    constructor(private auth: Auth, private authService: AuthenticationService, private router: Router, private notifService: NotificationService) { }

    // =====================================================
    ngOnInit()
    {
        // Listen to login change notifications & act accordingly
        this.subscription = this.notifService.loginStatusChanged$.subscribe(
            () => {
                // Update login status
                this.loggedIn = this.auth.loggedIn();
            }
        );
    }
    // =====================================================
}


登录菜单组件

import { AuthenticationService } from 'app/includes/services/auth-services/authentication.service';

@Component({
    selector     : 'app-loggedin-menu',
    template     : `<a (click)="logOut()">Log Out</a>`,
    encapsulation: ViewEncapsulation.None,
    providers    : [AuthenticationService],
})
export class LoggedinMenuComponent
{
    // =====================================================
    constructor(private authService: AuthenticationService, private router: Router) { }

    // =====================================================
    logOut()
    {
        this.authService.logout();

        // logout successful, redirect to home page
        this.router.navigateByUrl('/');
    }
    // =====================================================
}


通知服务

import { Injectable } from '@angular/core';
import { Subject    } from 'rxjs/Subject';

@Injectable()
export class NotificationService
{
    // Observable string sources
    private loginChangedSource = new Subject<boolean>();

    // Observable string streams
    loginStatusChanged$ = this.loginChangedSource.asObservable();

    // Service message commands
    updateLogin() { this.loginChangedSource.next(); }
}


认证服务

@Injectable()
export class AuthenticationService
{
    public token: string;

    constructor(private http: Http, private notifService: NotificationService) { }

    // =====================================================
    login(user: ILoginModel)
    {
        return this.http.post(this.appURL + 'api/account/login/', user)
            .map((response: Response) =>
            {
                // login successful if there's a jwt token in the response
                const token    = response.json() && response.json().token;
                if (token)
                {
                    // set token property
                    this.token = token;

                    // store username and jwt token in local storage to keep user logged in between page refreshes
                    localStorage.setItem('access_token', JSON.stringify({ username: user.UserName, token: token }));

                    // Notify other components to change top-right nav info accordingly
                    this.notifService.updateLogin();

                    // return true to indicate successful login
                    return '';
                } else
                {
                    // return false to indicate failed login
                    return response.text();
                }
            })
            .catch(this.handleError);
    }

    // =====================================================
    logout()
    {
        // Clear token & remove user from local storage to log user out
        this.token = null;
        localStorage.removeItem(consts.tokenName);

        // Notify other components to change top-right nav info accordingly
        this.notifService.updateLogin();
    }
    // =====================================================
}

有什么建议吗?

最佳答案

天哪!我花了 2 天时间尝试调试这个东西,实际上是在发布我的问题后 2 分钟;我意识到我必须从 TopNavComponent .ts

的提供程序列表中删除 NotificationService

providers: [Auth, NotificationService, AuthenticationService]

以防万一有人遇到这个问题!

关于angular - 显示访客的注册/登录链接,登录时隐藏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44692599/

相关文章:

dependency-injection - Angular 2 - 依赖注入(inject)和桶装

angular - 服务通知的组件

angularjs - Angular 服务的简单单元测试

angularjs - Angular View 在 http 拦截器之后不会更新

angular - 每个(一组)组件的 Angular 服务的单独实例

javascript - 如何使用 moment.js 动态获取去年九月的日期

angular - ngx-datatable 不能在环境上下文中声明访问器

angularjs - Angular 2 中接口(interface)的命名约定是什么?

Angular 5 HttpInterceptor 错误处理首先调用调用者的错误处理

angular - 我们什么时候应该使用 Angular 服务?