Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 角度2:从组件获取更新的服务属性_Angular_Typescript_Angular2 Services - Fatal编程技术网

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

Angular 角度2:从组件获取更新的服务属性,angular,typescript,angular2-services,Angular,Typescript,Angular2 Services,我的Angular 2应用程序使用路由保护将导航限制为经过身份验证的用户。这发生在位于我的AppModule中的auth-guard.service.ts中 当用户登录时,user.service.ts中的isAuthenticated属性设置为true,该属性位于名为FrameworkModule的单独模块中 用户服务是框架模块中的一个提供者,在应用程序模块中导入 我的问题:在auth guard内部,获取isAuthenticated值不起作用。它返回最初硬编码的值,而不是最近更新的版本。据

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

当用户登录时,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({});
    }

} 
从“@angular/core”导入{Injectable};
从“framework/users/UserApi”导入{UserApi};
从“rxjs/Observable”导入{Observable};
从'@angular/Http'导入{Http,Response};
导入“rxjs/add/observable/of”;
导入“rxjs/add/operator/delay”;
导入'rxjs/add/operator/mergeMap';
导入“rxjs/add/observable/throw”;
导入“rxjs/add/operator/catch”;
导入'rxjs/add/operator/map';
从“@angular/Router”导入{Router}”;
@可注射()
导出类UserService实现UserApi{
构造函数(专用路由器:路由器,专用http:http){
}
isAuthenticated:布尔值=false;
专用url=https://api.backendless.com/09CC17DE-A1D2-5E58-FF59-1E73BAF40800/8B920997-09FC-BC85-FFA1-8211B837A300/users/login';
私有数据={
登录名:“,
密码:“
};
signIn(用户名:string,密码:string,记忆:boolean):可观察{
this.data.login=用户名;
this.data.password=密码;
返回this.http.post(this.url,this.data)
.map(此.extractData)
.接住(这个.把手错误);
}
私有数据(res:Response){
this.isAuthenticated=true;
让body=res.json();
返回body.data |{};
}
私有句柄错误(错误:响应|任意){
//在现实世界的应用程序中,您可能会使用远程日志记录基础设施
让errMsg:string;
if(响应的错误实例){
const body=error.json();
const err=body.error | | JSON.stringify(body);
errMsg=`${error.status}-${error.statusText | |'''}${err}`;
}否则{
errMsg=error.message?error.message:error.toString();
}
控制台错误(errMsg);
返回可观察抛出(errMsg);
}
signOut():可观察{
this.isAuthenticated=false;
this.router.navigate(['/sign']);
({})的可观测返回;
}
} 

在初始化两个服务后,登录操作何时更改isAuthenticated的vlaue。在验证guard checks之前,一种可能的解释是,在使用guard确定此路线是否可导航后,正在运行将
isAuthenticated
设置为true的代码。我不确定您的登录工作流是什么样子的,但您是否从一个组件登录,然后尝试访问另一个组件?我没有看到任何人订阅调用
signIn
的结果,但是如果没有人订阅,那么我建议,在成功验证后,使用
@angular/Router
中的
路由器
服务,在成功验证后重定向到您希望他们去的地方。在应用程序模块之外的框架模块中进行登录。路由器和防护装置位于应用程序模块中。在调试时,用户服务正在按预期更新isAuthenticated bool,但当auth guard随后检查它时,它仍然以某种方式返回false。这就像有2个服务实例一样,但登录构造函数表明它只被命中一次。有一些基本的东西我遗漏了,我就是想不出来。