角度可观察不起作用

时间:2018-05-21 14:15:58

标签: angular firebase firebase-authentication angular6

我正在尝试将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() {}
}

WindowService:

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

问题是当reCAPTCHA解决后我得到了解决问题&#34;登录到控制台,但是observable不会更新(它为null)。

1 个答案:

答案 0 :(得分:2)

使用来源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() {}
}
相关问题