我正在尝试将登录用户的详细信息提供给我的应用程序。我有以下代码在Angular 5中可用,但在Angular 6中不起作用,因为rxjs 6中缺少.share()函数
我需要.share()函数吗?关于rxjs 6的更改,我的代码看起来还可以吗?
export class UserService {
readonly baseUrl = `${environment.apiUrl}/auth`;
private loggedIn = false;
private currentUserSubject = new BehaviorSubject<LoggedInUser>({} as LoggedInUser);
currentUser = this.currentUserSubject.asObservable().share();
constructor(private http: HttpClient) { }
login(userLogin: UserLogin) {
return this.http.post<any>(this.baseUrl + '/login', { username: userLogin.email, password: userLogin.password })
.subscribe(result => {
localStorage.setItem('auth_token', result.auth_token);
this.setCurrentUser();
return true;
});
}
setCurrentUser(): void {
if (localStorage.getItem("auth_token")) {
let jwtData = localStorage.getItem("auth_token").split('.')[1]
let decodedJwtJsonData = window.atob(jwtData)
let decodedJwtData = JSON.parse(decodedJwtJsonData)
this.currentUserSubject.next(
{
firstName: decodedJwtData.given_name,
id: decodedJwtData.id,
}
);
}
}
getCurrentUser(): LoggedInUser {
if (this.currentUserSubject.value.id) {
return this.currentUserSubject.value;
}
}
ngOnDestroy() {
this.currentUserSubject.unsubscribe();
}
isLoggedIn() {
this.setCurrentUser();
if (this.currentUserSubject.value.id) {
return true;
}
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
RxJS v5.5.2+已经转移到Pipeable运算符上,以改善树状抖动并简化创建自定义运算符的过程。现在operators需要使用“ 参考此新导入 ” pipe方法进行组合
import { share} from 'rxjs/operators';
Run Code Online (Sandbox Code Playgroud)
修改后的代码
currentUser = this.currentUserSubject.asObservable().pipe(share());
Run Code Online (Sandbox Code Playgroud)
RxJS 6 - What Changed? What's New?
我需要.share()函数吗?
根据您的用例,如果您不使用多个异步pipe ,则不需要share操作员
Subject 充当源Observable和多个之间的桥梁/代理observers,从而使多个observers共享同一Observable执行成为可能。
异步管道不使用共享,也没有对模板中的多次重复使用进行任何优化。它为模板中异步管道的每次使用创建预订。
参考:
RxJS: Understanding the publish and share Operators
| 归档时间: |
|
| 查看次数: |
1494 次 |
| 最近记录: |