tryToLogin(email:string,password:string) {
var success:boolean
this.auth.signInWithEmailAndPassword(email, password)
.then((firebaseUser)=>{
// on success
success = true
})
.catch(function(error) {
//on fail
var errorCode = error.code;
var errorMessage = error.message;
success = false
}).finally(()=>{
return success
})
}
这个不行。它返回未定义。
任何想法(也许以某种方式使用异步、等待和承诺)
我不确定这是否是您想要的。但是您可以使用 RxJS 将 promise 转换为 observablemap
并应用诸如map
和 之类的运算符catchError
来返回success
您需要的变量。
import { from, of } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
tryToLogin(email: string, password: string): Observable<any> {
return from(this.auth.signInWithEmailAndPassword(email, password)).pipe(
map(firebaseUser => {
// on success
return true;
}),
catchError(error => {
// on error
return of(false); // <-- you need to return an observable from `catchError` - so use `of`
})
);
}
现在,由于您返回的是 observable 而不是 Promise,因此您可以订阅使用它的函数。
this.someService.tryToLogin(...).subscribe(
res => console.log(res), // <-- will print `true` on successful login and `false` on failed login
error => { }
);
但是,如果您希望获得error
通知而不是next
通知,则需要从catchError
块中抛出错误。你可以使用 RxJSthrowError
函数。
import { throwError, from } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
tryToLogin(email: string, password: string): Observable<any> {
return from(this.auth.signInWithEmailAndPassword(email, password)).pipe(
map(firebaseUser => {
// on success
return true;
}),
catchError(error => {
// on error
return throwError(false); // <-- use `throwError` to emit an `error` notification
})
);
}
现在错误将在error
回调中捕获
this.someService.tryToLogin(...).subscribe(
res => console.log(res), // <-- will print `true` on successful login
error => console.log(error) // <-- will print `false` on failed login
);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句