【发布时间】:2021-05-19 14:14:07
【问题描述】:
在我的 Angular2 项目中,我曾经创建一个服务来关心系统身份验证,并且在这个服务上,我将用户数据存储在一个可观察对象上。
我想避免重复创建一个局部变量并在每个需要使用或操作存储在服务上的用户数据的单个组件中订阅这个 observable。
我能否以一种漂亮的方式简化对这些信息的访问?
export class AuthenticationService {
private readonly api_url: string = environment.API_URL;
private currentUserSubject: BehaviorSubject<User>;
public currentUser: Observable<User>;
constructor(private http: HttpClient) {
// Get data from local storage in case the page refreshes
let obj = JSON.parse(localStorage.getItem('auth'));
this.currentUserSubject = new BehaviorSubject<User>(obj ? obj.user : null);
this.currentUser = this.currentUserSubject.asObservable();
}
login(username: string, password: string) {
let _this = this;
return this.http.post<any>(this.api_url + 'login/', { "username": username, "password": password }).pipe(map(response => {
// login successful if there's a user and a token in the response
if (response.user && response.token) {
// store user details in local storage to keep user logged in between page refreshes
localStorage.setItem('auth', JSON.stringify(response));
this.currentUserSubject.next(response.user);
}
return response;
}));
}
logout(): void {
localStorage.removeItem('auth');
this.currentUserSubject.next(null);
}
}
这是我想要避免对所有需要访问数据的组件执行的操作:
export class LoginComponent implements OnInit {
currentUser: User;
ngOnInit() { }
constructor(
private authenticationService: AuthenticationService) {
this.authenticationService.currentUser.subscribe(user => {
this.currentUser = user;
});
}
}
【问题讨论】:
标签: angular global-variables angular2-services globalization