替换 rxjs6 中的 share() 函数

2024-02-22

我正在尝试让我的应用程序可以使用已登录用户的详细信息。我有以下代码,它在 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;
    }

}

RxJS v5.5.2+已移至Pipeable运算符来改善树摇动并使创建自定义运算符变得更容易。 现在operators需要结合使用pipe method
参考这个 https://blog.angularindepth.com/rxjs-understanding-lettable-operators-fe74dda186d3
新进口

import { share} from 'rxjs/operators';

修改代码

   currentUser = this.currentUserSubject.asObservable().pipe(share());

RxJS 6 - What Changed? What's New? https://www.academind.com/learn/javascript/rxjs-6-what-changed/

我需要 .share() 函数吗?

取决于您的用例,如果您不使用多个异步pipe你不需要share操作员
Subject充当源之间的桥梁/代理Observable还有很多observers,使得可以有多个observers分享相同的Observable执行。

异步管道不使用共享,也不对模板中的多次重复使用进行任何优化。它为模板中每次使用异步管道创建订阅。

Refer: RxJS: Understanding the publish and share Operators https://blog.angularindepth.com/rxjs-understanding-the-publish-and-share-operators-16ea2f446635

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

替换 rxjs6 中的 share() 函数 的相关文章

随机推荐