首页 > 解决方案 > 如何从订阅者获取结果作为函数的返回值?

问题描述

我想根据我在订阅者方法中得到的结果设置 canActivate 函数的布尔值。然而,这给了我一个错误说:A function whose declared type is neither 'void' nor 'any' must return a value.我无法确定我的代码到底有什么问题,我该如何修改它才能工作?

import { Injectable } from '@angular/core';
import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot} from '@angular/router';
import {ApiService} from '../api.service';

@Injectable({
  providedIn: 'root'
})
export class ProblemAuthGuard implements CanActivate {

  constructor(private apiService: ApiService,
              private router: Router) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    this.apiService.canEdit(route.params['id'])
      .subscribe(obj => {
        if (obj['result'] === 'public') {
          this.router.navigate(['403']);
          return false;
        } else {
          return true;
        }
      });
  }

}

以下是canEditfrom 方法的实现apiService

import { Injectable } from '@angular/core';
import { environment} from '../environments/environment';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';


const apiUrl = environment.apiURL;

@Injectable({
  providedIn: 'root'
})
export class ApiService {

  constructor(private http: HttpClient) {}

  canEdit(problemId: number): Observable<any> {
    return this.http.get(apiUrl + '/archive/problems/' + problemId + '/visibility');
  }

}

标签: angular

解决方案


canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    this.apiService.canEdit(route.params['id'])
      .subscribe(obj => {
        if (obj['result'] === 'public') {
          this.router.navigate(['403']);
          return false;
        } else {
          return true;
        }
      });
  }

在这里你并没有真正返回任何东西,你说你的方法将返回布尔值。

return falsereturn true返回您的订阅功能,而不是canActivate功能。

但是由于您是异步获取数据,因此根本无法返回布尔值,您仍然必须返回 Observable。

将您的代码更改为:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
    return this.apiService.canEdit(route.params['id'])
      .pipe(map(obj => {
        if (obj['result'] === 'public') {
          this.router.navigate(['403']);
          return false;
        } else {
          return true;
        }
      }));
  }

这样你就可以将布尔值的 Observable 返回给你的警卫(警卫可以接收boolean,Observable<boolean>Promise<boolean>)。


推荐阅读