Rxjs 在switchmap内部进行http调用

Rxjs 在switchmap内部进行http调用,rxjs,observable,Rxjs,Observable,我正在用firebase auth和dotnet core后端编写一个angular应用程序。我正在尝试创建一个服务,以便跟踪firebase uid并跟踪用户是否是从后端服务器获得的管理员。我可以顺利地从firebase获取uid,但当我尝试从api获取用户对象时,控制台中会出现错误 以下是我的用户服务中的代码: export class UserService { uid = this.afAuth.authState.pipe( map(authState =>

我正在用firebase auth和dotnet core后端编写一个angular应用程序。我正在尝试创建一个服务,以便跟踪firebase uid并跟踪用户是否是从后端服务器获得的管理员。我可以顺利地从firebase获取uid,但当我尝试从api获取用户对象时,控制台中会出现错误

以下是我的用户服务中的代码:

export class UserService {
    uid = this.afAuth.authState.pipe(
        map(authState => {
            return !authState ? null : authState.uid;
        })
    );

    isAdmin = this.uid.pipe(
        switchMap(uid => {
            if (uid) {
                console.log("there is a uid")
                this.httpClient.get<User>("https://localhost:44337/api/users/" + uid).subscribe(data => {
                    console.log(data.isAdmin); // prints 'true'
                    return observableOf(data.isAdmin);
                });
            } else {
                return observableOf(false);
            }
        })
    );

    constructor(
        private afAuth: AngularFireAuth,
        private httpClient: HttpClient) { }
}

在switchMap操作符中,您不应该直接订阅可观察的。您应该返回observable,switchMap操作符将为您处理订阅

switchMap(uid => {
            if (uid) {
                console.log("there is a uid")
                return this.httpClient.get<User>("https://localhost:44337/api/users/" + uid).pipe(map(data => {
                    console.log(data.isAdmin); // prints 'true'
                    return data.isAdmin
                }));
            } else {
                return of(false);
            }
        })


非常感谢!那太简单了!