替换rxjs6中的share()函数 [英] Replacing the share() function for in rxjs6
问题描述
我正在尝试将登录用户的详细信息提供给我的应用程序.我有以下在Angular 5中工作的代码,但在Angular 6中不工作,因为rxjs 6中缺少.share()函数
I'm trying to have the details of the logged in user available to my application. I have the following code which worked in Angular 5, but doesn't work in Angular 6 because the .share() function is missing in rxjs 6
我需要.share()函数吗?关于rxjs 6的更改,我的代码看起来还可以吗?
Do I need the .share() function? Does my code look ok with regards to the changes for 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;
}
}
推荐答案
RxJS v5.5.2 +
已移至 Pipeable
运算符,以改善树抖动并使其更易于创建自定义运算符.现在,需要使用 pipe
方法将 operator
组合起来
RxJS v5.5.2+
has moved to Pipeable
operators to improve tree shaking and make it easier to create custom operators.
now operators
need to be combined using the pipe
method
Refer This
New Import
import { share} from 'rxjs/operators';
修改后的代码
currentUser = this.currentUserSubject.asObservable().pipe(share());
我需要.share()函数吗?
Do I need the .share() function?
取决于您的用例,如果您不使用多个异步 pipe
,则不需要 share
运算符 Subject
充当源 Observable
和许多 observers
之间的桥梁/代理,这使得多个 observers
可以共享相同的 Observable
执行.
Depends on your use case, if you aren't using multiple async pipe
you don't require share
operator
Subject
acts as a bridge/proxy between the source Observable
and many observers
, making it possible for multiple observers
to share the same Observable
execution.
异步管道不使用共享,也没有对模板中的多次重复使用进行任何优化.它会为模板中Async管道的每次使用创建一个订阅.
引用 : RxJS:了解发布和共享运营商代码>
这篇关于替换rxjs6中的share()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!