angular - 如何从订阅者获取结果作为函数的返回值?
问题描述
我想根据我在订阅者方法中得到的结果设置 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;
}
});
}
}
以下是canEdit
from 方法的实现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');
}
}
解决方案
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 false
并return 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>
)。
推荐阅读
- php - 如何在 PHP 中使用 XPath 解析这个 XML
- scala - scala.Some 无法转换为 scala.collection.immutable.Map 异常
- java - 测试期间的 Spring MockMVC、Spring 安全性和全局方法安全性
- sql - 如何从oracle中的时间戳列中删除最后几个额外的零?
- google-cloud-platform - GCP-使用php将文件从云存储加载到bigquery时尝试更改默认位置时
- javascript - Hyperledger Composer:访问本地系统上的文件
- reactjs - 反应提示“未知助手 getPrototypeOf”的模块构建失败
- yii2 - 更新操作中的 Yii2 搜索字段
- java - onResponse 内的空 ArrayList
- lua - 如何从redis中的多个哈希中获取HGET