【发布时间】:2020-12-25 20:11:47
【问题描述】:
在我的后端 - express.js 中,我成功返回了一个布尔值,它告诉我用户是否存在。
问题出在我的前端 - angular(最新版本),当我收到该值时,我需要在异步执行后立即使用该值。
所以我决定使用 RxJS 管道 + 地图
我明白了:
Argument of type 'Observable<unknown>' is not assignable to parameter of type 'OperatorFunction<boolean, unknown>'.
Type 'Observable<unknown>' provides no match for the signature '(source: Observable<boolean>): Observable<unknown>'.ts(2345)
The 'this' context of type 'void' is not assignable to method's 'this' of type 'Observable<unknown>'.
ApiService.ts
checkIfUserExists(email: string): Observable<boolean> {
return this.http.get<boolean>(`${this.COINS_URL}/login/check/${email}`);
}
register.component.ts
let value = null
this.apiService.checkIfUserExists(this.user.email)
.pipe(
map(data => console.log(data))
)
console.log(value) -- returns [object Object]
如何解决这个问题并成功使用管道+地图?
为 cmets 编辑:
checkIfUserExists() {
this.user = this.userRegistrationForm.value
return this.apiService.checkIfUserExists(this.user.email)
.pipe(
map(data => data))
.subscribe(e => e.userExists)
}
尝试使用时 - 我得到 [object Object]
userExists = this.checkIfUserExists()
console.log('userExists: ' + userExists)
编辑 2:最终解决方案,感谢所有帮助 使用回调解决了问题 非常感谢这篇文章:How do I return the response from an asynchronous call?
代码:
checkIfUserExists(callback) {
this.user = this.userRegistrationForm.value
console.log("2. callback here is the function passed as argument above...")
this.apiService.checkIfUserExists(this.user.email)
.pipe(
map(data => data))
.subscribe(e => {
console.log("3. start async operation...")
console.log("4. finished async operation, calling the callback, passing the result...")
callback(e.userExists)
})
}
onSubmit() {
let userExists = null
console.log("1. function called...")
this.checkIfUserExists((result: boolean) => {
// 5. Received the result from the async function,
// now do whatever you want with it:
console.log("5. result is: ", result);
userExists = result
this.userExistsValidator(userExists)
});
}
【问题讨论】:
-
您也可以选择接受以下任何一个答案 1. 在这种情况下无需订阅两次 2. 如果您对
userExists属性感兴趣,那么您可以项目从地图运营商即.map(data => data.userExists)和订阅块中,您可以直接访问布尔值,如.subscribe(e => console.log(e));
标签: angular rxjs observable angular2-observables