两个订阅解析后,从服务方法返回Observable <boolean>

Ben*_*cot 10 rxjs typescript rxjs5 angular

我正在尝试设置一种简单的方法来将当前用户名与Angular服务中的配置文件用户名进行比较.

显然,在我可以比较它们之前,配置文件用户名和用户的用户名必须解决,那么如何返回一个布尔值observable以便我可以在组件中订阅这个比较?

这就是我所在的地方:

public profileId = new Subject<string>; // Observable string source updated from a profile.component (when the URL displays the profile's username)
public profileId$ = this.profileId.asObservable();
public currentUser = this.principal.asObservable().distinctUntilChanged();

public isProfileOwner(): Observable<boolean> { // A function whose declared type is neither 'void' nor 'any' must return a value.
    this.currentUser.subscribe(user => {
            this.profileId$.subscribe(
                profile => {
                    console.log(profile + ' ' + user.username); // match!
                    if (profile === user.username) {
                        return Observable.of(true);
                    } else {
                        return Observable.of(false);
                    }
                }
            )
        })
}
Run Code Online (Sandbox Code Playgroud)

这似乎是其他SO答案解释的方式,但我得到了 [ts] A function whose declared type is neither 'void' nor 'any' must return a value.

我想订阅组件内的测试.

this.authService.isProfileOwner().subscribe(
    data => {
        console.log(data); // should be boolean
    }
)
Run Code Online (Sandbox Code Playgroud)

小智 8

这可以通过主题来实现

import { Subject } from 'rxjs';

public isProfileOwner(): Observable<boolean> {
        var subject = new Subject<boolean>();

        this.currentUser.subscribe(user => {
                this.profileId$.subscribe(
                    profile => {
                        console.log(profile + ' ' + user.username); // match!
                        if (profile === user.username) {
                            subject.next(true);
                        } else {
                            subject.next(false);

                        }
                    }
                )
            })
            return subject.asObservable();
    }
Run Code Online (Sandbox Code Playgroud)


use*_*994 5

我个人建议使用forkJoin,等待可观察对象,然后将flatMap转换为Observable<boolean>

return Observable.forkJoin(this.currentUser, this.profileId$).flatMap(
    results => {
        user = results[0];
        profile = results[1];
        return Observable.of(profile === user.username)
    }
);
Run Code Online (Sandbox Code Playgroud)


AJT*_*T82 5

正如@ user184994的其他答案所指出的,forkJoin在这种情况下将不起作用。相反,您可以使用combineLatest,然后非常类似于@ user184994,否则实现了服务代码:

isProfileOwner(): Observable<boolean> {
  return Observable.combineLatest(this.currentUser, this.profileId$)
    .map(results => {
       let user = results[0];
       let profile = results[1];
       return (user.username === profile)
    });
}
Run Code Online (Sandbox Code Playgroud)

演示