为什么我会收到错误 Type 'Subscription' is missing on the function?

Why do I get error Type 'Subscription' is missing on the function?

我有这个方法:

  isRouteAccessible(token: string): Observable<boolean> {

  return this.loginHttpService.isPasswordRecoveryTokenValid(token).subscribe(x => {
      if (x) {
        return of(true)
      }
      this.router.navigate(['/authentication/signin'])
      return of(false)
    })

  }

这里是 isPasswordRecoveryTokenValid 的定义:

  isPasswordRecoveryTokenValid(token: string): Observable<boolean> {
    return this.http.get<boolean>(environment.baseUrl + '/auth/validateTokenPasswordRecovery', {
      params: {
        token
      }
    })
  }

我在 isRouteAccessible 上收到此错误:

 Type 'Subscription' is missing the following properties from type 'Observable<boolean>': _isScalar, source, operator, lift, and 6 more.
 

为什么我在 isRouteAccessible 函数上会出现这个错误?

您正在 return 进行订阅,因为您订阅了一个 Observable,它不同于 'isRouteAccessible' 的 return 类型(Observable)。

要解决此问题,请在 'isRouteAccessible' 中更改 'isPasswordRecoveryTokenValid' 的结果,然后 return 更改后的结果:

isRouteAccessible(token: string): Observable<boolean> {
    return this.loginHttpService.isPasswordRecoveryTokenValid(token)
        .pipe(
            map((x) => {        // map the result from 'isPasswordRecoveryTokenValid' to a true/false result
                if (x) {        // check for whatever result that is returned from the API at /auth/validateTokenPasswordRecovery 
                    return true;
                }
                
                this.router.navigate(['/authentication/signin']);
                return false;
            })
        );
}

// then, subscribe to 'isRouteAccessible' like so:
demoCallerFunction() {
    this.isRouteAccessible('token').subscribe((result: boolean) => {
        console.log(result);        // result is either true/false
    });
}

或者,如果你想订阅'isRouteAccessible',那么你必须在'isRouteAccessible'中检查和处理'isPasswordRecoveryTokenValid'的结果(并且不要return结果):

isRouteAccessible(token: string): void {
    this.loginHttpService.isPasswordRecoveryTokenValid(token)
        .subscribe((x) => {
            if (x) {            // check for whatever result that is returned from the API at /auth/validateTokenPasswordRecovery 
                // handle a case of 'true'
                return;
            }
            
            // handle a case of 'false'
            this.router.navigate(['/authentication/signin']);
        });
}