角度2:让组件自动检测服务中的变量更改 [英] Angular 2: have component auto detect variable change in a service

查看:58
本文介绍了角度2:让组件自动检测服务中的变量更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前面临的问题是在功能上,当用户登录时,我的导航栏不会自动更新以向他们显示正确的链接.仅当我手动刷新不需要的页面时,它才会更新,因为这是一个单页面的应用程序.因为注销按钮和功能位于控制导航栏的组件内,所以我可以处理确定"注销.但是,登录是通过auth服务控制的,并且对我的组件不可见.我试过公开isLoggedIn布尔值,然后将组件导入到auth服务中,并在登录时将该值设置为true,但这会产生非描述性的zone.js错误.请参阅下文-感谢所有帮助.

The issue I'm currently facing is that functionally, when a user logs in, my nav bar does not automatically update to show them the proper links. It will only update if I manually refresh the page which is not desired since this is a single page application. I can handle logging out OK since the logout button and functionality lives inside the component that controls the nav bar. However, logging in is controlled via an auth service and not visible to my component. I've tried making the isLoggedIn boolean public and then importing the component into the auth service and setting the value to true on login however this produces non-descript zone.js errors. Please see below- all help is appreciated.

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,它负责实际登录用户:

as you can see, isLoggedIn is set [properly] in the ngOnInit method and my component is updated appropriately when the logout button is clicked. What I'm struggling to figure out is how to update the isLoggedIn boolean in this component when a user logs in which occurs after this component's ngOnInit method has been executed. Just in case it's desired/needed, you can find the authentication.service below which is responsible for actually logging in a user:

@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.

In your component class, you can make isLoggedIn a property that gets the current value from the service. Angular's change detection mechanism will access it when appropriate and update the rendered HTML.

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

这篇关于角度2:让组件自动检测服务中的变量更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆