我如何仅在 finaly 块覆盖 firebase 登录中返回值

意大利
 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
  })
}

这个不行。它返回未定义。

任何想法(也许以某种方式使用异步、等待和承诺)

迈克尔·D

我不确定这是否是您想要的。但是您可以使用 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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章