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

时间:2017-06-22 07:15:49

标签: 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();
            }
        );
    }
    // =====================================================
}

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();
    }
    // =====================================================
}

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

天哪!我花了两天的时间尝试调试这个东西,并在发布我的问题后2分钟;我意识到我必须从NotificationService

中的提供商列表中删除TopNavComponent .ts
  

提供商:[Auth, NotificationService ,AuthenticationService]

以防有人遇到这个问题!