我不断收到以下错误消息:
Type '() => void' is not assignable to type '(MovingDirection: any) => boolean'
我要做的就是将订阅的结果用作布尔值而不是Observable。
canEnterStep2仅接受布尔值。
我需要以某种方式从canEnterStep2内部调用它,然后根据输出,返回布尔值true或false。
但是它似乎没有用,我被想法困扰了!
有解决方法吗?
canEnterStep2: (MovingDirection) => boolean = () => {
this.checkUsernameExists().subscribe(
res => {
if (res) {
// do some stuff here
return true
} else {
// do some stuff here
return false
}
})
}
checkUsernameExists(): Observable<boolean> {
return this.userService.getUserByUsername(this.username.toLowerCase().trim()).pipe(map(result => {
if (result) {
if ((result.length > 0) && (result[0]['username'] === this.username.toLowerCase().trim()) && (result[0]['uid'] !== this.user.uid)) {
this.logger.debug('Username belongs to another user');
return true;
} else {
this.logger.debug('Username does not belong to another user');
return false;
}
} else {
this.logger.debug('Username could not be determined');
return false
}
}));
}
答案 0 :(得分:1)
如果要异步检查某些条件,则必须一直保持异步状态。像
canEnterStep2: (MovingDirection) => Observable <boolean> = () => {
if (/* ...conditions... */) {
return this.setUserPersonalDetails();
} else {
// display and/or log error messages here, then:
return of(false);
}
}
setUserPersonalDetails(): Observable <boolean> {
// is ngxLoader an asynchronous function?
// if yes, make it the start of the observable chain, and switchMap()
this.ngxLoader.start();
return this.userService.getUserByUsername(this.username.toLowerCase().trim())
.pipe(
tap( /* do side effects here */ ),
map( /* check if result satisfies conditions, return true or false accordingly */ )
);
};
canEnterStep2
的使用者还必须将其视为异步流。