Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/27.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_Angular2 Services - Fatal编程技术网

Angular 角度2服务值不持久

Angular 角度2服务值不持久,angular,angular2-services,Angular,Angular2 Services,我创建了一个服务,用于获取用户并检查其权限。当我在应用程序中使用它时,我希望在整个应用程序中保留的值似乎会重置为每次调用getUser()方法时的值 因此,我的服务代码是: import { Injectable } from '@angular/core'; import { MyHttp } from '../my-http/my-http.service'; import { Response } from '@angular/http'; import { MyAuth } from '

我创建了一个服务,用于获取用户并检查其权限。当我在应用程序中使用它时,我希望在整个应用程序中保留的值似乎会重置为每次调用
getUser()
方法时的值

因此,我的服务代码是:

import { Injectable } from '@angular/core';
import { MyHttp } from '../my-http/my-http.service';
import { Response } from '@angular/http';
import { MyAuth } from '../my-auth.service';
import { MyAuthUser } from './my-auth-user.ts';
import { Observable } from 'rxjs';

@Injectable()
export class MyUserService {
    private currUser: MyAuthUser = {
        id: 'UNAUTHENTICATED_USER',
        name:'Anonymous',
        roles: []
    };

    constructor(private http: MyHttp, private auth: MyAuth) {}

    public extractData(res: Response): MyAuthUser {
        let user = res.json();
        this.currUser = Object.assign({}, user)
        return this.currUser;
    }

    public getUser(): Observable<MyAuthUser> {
        // Check if we already have user
        if(this.currUser.id === 'UNAUTHENTICATED_USER') {
            // Get user from tokeninfo endpoint
            return this.http.get('/myuserendpoint')
                .map(this.extractData);
        }
        else {
            // Either user is unauthenticated or user already exists, either way send back whatever is in this.currUser
            return Observable.create((observer:any) => {
                observer.next(this.currUser);
                observer.complete();
            });
        }
    }

    public hasRole(role: string): boolean {
        if(!this.currUser || this.currUser.id === 'UNAUTHENTICATED_USER') {
            throw new Error('User roles is undefined, make sure you call getUser');
        }

        return !!~this.currUser.roles.indexOf(role);
    }
}
然后我在我的根组件中使用它来获取用户并检查他们是否具有特定角色:

constructor(private userService: MyUser) {
    this.userService.getUser().subscribe((user) => {
        this.user = user;
        let isDeveloper = this.userService.hasRole('developer');
        console.log('IS DEV?: ', isDeveloper);
    });
}
因此,用户成功返回并设置为
this.user
,但是,当我运行
hasRole()
方法(该方法应该只检查服务的
currUser
值)时,它会以某种方式再次重置为
未经身份验证的用户。我不明白为什么这个值不能从一个方法调用持续到下一个方法调用


我对可观测性不是非常精通,所以我无法判断我在那里做的事情是否会弄乱它或者是什么。

如果传递的方法引用“this”,这种方式会导致麻烦

.map(this.extractData);
改用

.map(() => this.extractData())
或者如果它需要接受一个参数

.map((x) => this.extractData(x))

这样就保留了
的范围。

currUser
返回
未经验证的\u用户
的代码行的确切位置?问题是当
if
语句在
hasRole()
中运行时,
This.curruuser.id
再次等于
未经验证的\u用户
,尽管我刚刚被设置为http请求返回的用户。哦,是的,非常感谢!我完全错过了,非常感谢你的回答!
.map((x) => this.extractData(x))