Reputation: 1666
I have a service which I have created to handle getting a user and checking their permissions. When I use it in my app, the value I want to persist across the app appears to reset back to what it was every time I call a getUser()
method.
My service code is thus:
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);
}
}
I'm adding it as a provider in my app's bootstrap method:
bootstrap(MyAppComponent, [MyUser, ...]);
Then I am using it in my root component to get the user and check whether they have a specific role:
constructor(private userService: MyUser) {
this.userService.getUser().subscribe((user) => {
this.user = user;
let isDeveloper = this.userService.hasRole('developer');
console.log('IS DEV?: ', isDeveloper);
});
}
So the user comes back successfully and is set to this.user
, however when I run the hasRole()
method which should just check against the service's currUser
value, it is somehow reset to the UNAUTHENTICATED_USER
again. I can't figure out why this value is not persisting from one method call to the next.
I'm not super well versed in observables, so I can't tell if maybe something I'm doing there is messing with it or what.
Upvotes: 1
Views: 1079
Reputation: 657228
Passing method references this way causes troubles if the passed method refers to `this´
.map(this.extractData);
Use instead
.map(() => this.extractData())
or if it needs to accept a parameter
.map((x) => this.extractData(x))
This way the scope of this
is retained.
Upvotes: 2