首页 > 解决方案 > 角度可观察的不起作用

问题描述

我正在尝试将 Firebase 电话身份验证添加到我的应用程序中。我正需要创建一个 reCAPTCHA 对象。我想知道 reCAPTCHA 是否已解决。

在模板中:

{{ recaptchaSolved | async | json }}

这是我的组件类:

export class AddComponent implements OnInit, OnDestroy {
  windowRef: any;
  @ViewChild('recaptchaContainer') recaptchaContainer: ElementRef;
  recaptchaSolved: Observable<boolean>;

  constructor(
    private win: WindowService
  ) {}

  ngOnInit() {
    this.windowRef = this.win.windowRef;
    firebase.auth().useDeviceLanguage();

    this.windowRef.recaptchaVerifier = new firebase.auth.RecaptchaVerifier(
      this.recaptchaContainer.nativeElement, // for visible recaptcha
      {
        size: 'small',
        callback: response => {
          console.log(`reCAPTCHA solved`);
          this.recaptchaSolved = of(true);
        },
        'expired-callback': () => {
          console.log(`reCAPTCHA expired`);
          this.recaptchaSolved = of(false);
        }
      }
    );
  }

  ngOnDestroy() {}
}

窗口服务:

@Injectable()
export class WindowService {
  get windowRef() {
    return window;
  }
}

问题是当 reCAPTCHA 被解决时,我在控制台中记录了“reCAPTCHA 已解决”,但 observable 没有更新(它为空)。

标签: angularfirebasefirebase-authenticationangular6

解决方案


使用源Subject并观察它。

export class AddComponent implements OnInit, OnDestroy {
  recaptchaSolvedSource = new Subject<boolean>();
  recaptchaSolved = this.recaptchaSolved.asObservable();

  constructor(
    private win: WindowService
  ) {}

  ngOnInit() {
    ...
    this.windowRef.recaptchaVerifier = new firebase.auth.RecaptchaVerifier(
      this.recaptchaContainer.nativeElement, // for visible recaptcha
      {
        size: 'small',
        callback: response => {
          this.recaptchaSolvedSource.next(true);
        },
        'expired-callback': () => {
          this.recaptchaSolvedSource.next(false);
        }
      }
    );
  }

  ngOnDestroy() {}
}

推荐阅读