Angular2 唯一变量设置问题

Angular2 Unique variable setting issue

所以我一直在网上学习教程并且有一个简单的登录组件,但似乎没有像我预期的那样工作?我在下面有一个登录组件:

import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { FormGroup } from '@angular/forms';

// Services
import { AuthService } from '../../_services/auth.service';

@Component({
    styles: [require('./login.component.css')],
    template: require('./login.component.html'),
    providers: [AuthService]
})
export class LoginComponent {

    constructor(private _router: Router, private _authService: AuthService) {

    }

    login(form) {
        var email = form.form._value.email;
        var password = form.form._value.password;
        var response = this._authService.login(email, password);
        if (response) {
            this._router.navigate(['dashboard']);
        } else {
            console.log("error");
        }
    }
}

路由上设置的鉴权守卫CanActivate

import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';

import { AuthService } from '../_services/auth.service';

@Injectable()
export class AuthGuard implements CanActivate {
    constructor(private _router: Router, private _authService: AuthService) {

    }

    canActivate() {
        console.log("auth: " + this._authService.isLoggedIn);
        if (this._authService.isLoggedIn == true) {
            // logged in so return true
            return true;
        } else {
            // not logged in so redirect to login page
            this._router.navigate(['login']);
            return false;
        }
    }
}

最后我的身份验证服务实际负责登录,这又设置了一个变量,用于我的 canActivate 身份验证保护。

import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map'

@Injectable()
export class AuthService {
    isLoggedIn = false;

    constructor(private http: Http) { }

    login(username, password) {
        this.isLoggedIn = true;
        console.log("set: " + this.isLoggedIn);
        return true;
    }

    logout() {
        this.isLoggedIn = false;
    }
}

现在,当我 运行 登录函数时, isLoggedIn 变量已成功设置为真,但是当导航到仪表板时,警卫 运行 变量 isLoggedIn 是设置为假。现在在我看来,我希望它是真的,因为我在登录功能为 运行.

时设置了它

非常感谢。罗斯

providers: [AuthService]

在您的组件中告诉 Angular 为组件的每个实例创建并注入一个 AuthService 实例。因此,您在组件中获得的 AuthService 实例与您在其他服务中可能从 NgModule 提供商获得的实例不同。

只需删除该行,并在根 NgModule 中声明一个且只有一个 AuthService 提供者,这样应用程序中的每个组件和服务都将共享它。