Angular 2:从组件获取更新的服务属性

时间:2017-06-01 19:59:46

标签: angular typescript angular2-services

我的Angular 2应用程序使用路由保护来限制导航到经过身份验证的用户。这发生在auth-guard.service.ts中,它位于我的AppModule

当用户登录时,在User.service.ts中将isAuthenticated属性设置为true,该属性位于名为FrameworkModule的单独模块中。

用户服务是框架模块中的提供程序,它在应用程序模块中导入。

我的问题:在auth-guard内部,获取isAuthenticated值不起作用。它返回最初硬编码的值,而不是最近更新的版本。据我所知,这个属性应该是一个单例,属性值应该保持不变。我在这里错过了一些基本原理吗?

AuthGuard

import { Injectable }     from '@angular/core';
import { CanActivate, CanActivateChild, Router }    from '@angular/router';
import { UserService } from "framework/services/user.service";


@Injectable()
export class AuthGuard implements CanActivate, CanActivateChild {

    //protect and restrict routes
    constructor(private userService: UserService, private router: Router) {}

    canActivate() : boolean {
    console.log('AuthGuard#canActivate called ' + this.userService.isAuthenticated );

        let authenticated:boolean = this.userService.isAuthenticated;

        if (!authenticated) {
            console.log('not auth');
            this.router.navigate(['/signin']);
        }
        return this.userService.isAuthenticated;
    }

    canActivateChild() : boolean {
        return this.canActivate();
    }
}

用户服务

import { Injectable } from "@angular/core";
import { UserApi } from "framework/users/user-api";
import { Observable } from "rxjs/Observable";
import { Http, Response } from '@angular/http';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/delay';
import 'rxjs/add/operator/mergeMap';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import { Router } from "@angular/router";

@Injectable()
export class UserService implements UserApi{
    constructor(private router: Router, private http: Http) {
    }

    isAuthenticated:boolean = false;    

    private url = 'https://api.backendless.com/09CC17DE-A1D2-5E58-FF59-1E73BAF40800/8B920997-09FC-BC85-FFA1-8211B837A300/users/login';
    private data = {
        login : " ",
        password : " "
    };


    signIn(username: string, password: string, rememberMe: boolean): Observable<any> {
        this.data.login = username;
        this.data.password = password;
        return this.http.post(this.url, this.data)
                    .map(this.extractData)
                    .catch(this.handleError);
    }

    private extractData(res: Response) {
        this.isAuthenticated = true;
        let body = res.json();
        return body.data || { };
    }

    private handleError (error: Response | any) {
        // In a real world app, you might use a remote logging infrastructure
        let errMsg: string;
        if (error instanceof Response) {
            const body = error.json() || '';
            const err = body.error || JSON.stringify(body);
            errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
        } else {
            errMsg = error.message ? error.message : error.toString();
        }
        console.error(errMsg);
        return Observable.throw(errMsg);
    }

    signOut(): Observable<any>{
        this.isAuthenticated = false;
        this.router.navigate(['/signin']);
        return Observable.of({});
    }

} 

0 个答案:

没有答案