Angular 2 Service值不持久

时间:2016-05-20 16:58:05

标签: 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 '../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);
    }
}

我在应用程序的引导程序中将其添加为提供程序:

bootstrap(MyAppComponent, [MyUser, ...]);

然后我在我的根组件中使用它来获取用户并检查他们是否具有特定角色:

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值,它是以某种方式再次重置为UNAUTHENTICATED_USER。我无法弄清楚为什么这个值不会从一个方法调用持续到下一个。

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

1 个答案:

答案 0 :(得分:2)

如果传递的方法引用“this”

,则以这种方式传递方法引用会导致麻烦
$('input[name=career]').change(function() {
    if (this.value == '1') {

        // check if autosuggest has not already been initialized
        if (typeof as_json === 'undefined') {

           // input element is inserted into the page
           $(".tp").html('<input type="text" class="form-control input-lg" name="college" id="college" placeholder="College name">');

           // initialize autosuggest here
           var as_json = new bsn.AutoSuggest('college', options);
       }

    }

});

改为使用

.map(this.extractData);

或者是否需要接受参数

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

这样就可以保留.map((x) => this.extractData(x)) 的范围。