我目前面临的问题是,功能上,当用户登录时,我的导航栏不会自动更新以显示正确的链接。只有当我手动刷新不需要的页面时,它才会更新,因为这是一个单页面应用程序。我可以处理注销记录,因为注销按钮和功能位于控制导航条的组件内。但是,登录是通过AuthService来控制的,而对于我的组件来说是不可见的。我曾尝试制作isLoggedIn布尔公有,然后将组件导入到AuthService中,并在登录时将其设置为true,但是这会产生非描述性的ZONE.JS错误。请看下面-感谢所有帮助。
app.component它控制我的导航栏:

export class AppComponent implements OnInit{
    private isLoggedIn: boolean;

    constructor(private router: Router, private authenticationService: AuthenticationService) { }

    ngOnInit() {
        this.isLoggedIn = this.authenticationService.isLoggedIn();
    }

    logout() {
        this.isLoggedIn = false;
        this.authenticationService.logout();
        this.router.navigate([""]);
    }

    title = 'MYlestone';
}

以及app.component模板:
<div class="site-container">
    <nav class="navbar navbar-toggleable-md">
        <div *ngIf="isLoggedIn">
            <span class="navbar-brand text-color">MYlestone</span>
        </div>
        <div *ngIf="!isLoggedIn">
            <span class="navbar-brand text-color" [routerLink]="['']" style="cursor:pointer">MYlestone</span>
        </div>
        <div>
            <div class="navbar-nav" *ngIf="isLoggedIn">
                <a class="nav-item nav-link" href="#" [routerLink]="['content']">My Content</a>
                <a class="nav-item nav-link" href="#" [routerLink]="['about']">About</a>
                <div class="ml-auto">
                    <a class="nav-item nav-link" href="#" (click)="logout()">Logout</a>
                </div>
            </div>
        </div>
    </nav>
    <div class="container-fluid text-color">
        <!-- let client side routing take over, see app.routing.ts -->
        <router-outlet></router-outlet>
    </div>
</div>

如您所见,在ngoninit方法中,isLoggedIn被[正确地]设置,并且当单击注销按钮时,我的组件被适当地更新。我正在努力弄清楚的是,当用户登录时,如何更新该组件中的isLoggedIn布尔值,这是在执行该组件的ngoninit方法之后发生的。如果需要,您可以在下面找到authentication.service,它负责实际登录用户:
@Injectable()
export class AuthenticationService {
    constructor(private http: Http) { }

    login(email: string, password: string) {
        return this.http.post('http://localhost:36000/api/accounts/authenticate', { email: email, password: password })
            .map((response: Response) => {
                let user = response.json();
                if (user && user.token) {
                    localStorage.setItem('currentUser', JSON.stringify(user));
                }
            });
    }

    logout() {
        localStorage.removeItem('currentUser');
    }

    isLoggedIn() {
        //check to see if token exists
        if (localStorage.getItem('currentUser')) {
            return true;
        }
        else {
            return false;
        }
    }
}

最佳答案

在组件类中,可以将isLoggedIn设置为从服务获取当前值的属性。Angular的变化检测机制将在适当的时候访问它并更新呈现的HTML。

public get isLoggedIn(): boolean {
    return this.authenticationService.isLoggedIn();
}

10-05 20:52
查看更多