网站搜索

TypeScript - 如何验证用户并保存他们的详细信息


我已经尝试阅读 angularfire2 文档,并且已经进行到这里。我的认证服务调用 angularfire.auth.login。我已经订阅了这个函数,并且我想将返回的用户信息保存到数据库中。

TypeScript 编译器返回错误:

错误: Typescript 发现以下错误: /Users/macbook/dev/app/kichenclub/tmp/broccoli_type_script_compiler-input_base_path-nMnfGgj9.tmp/0/src/app/auth.service.ts (12, 25): 属性 'displayName' 在类型 'FirebaseAuthState' 上不存在。

并且所有 'displayName' 也是一样。

我甚至走在正确的方向上吗?还有什么其他方法可以解决这个问题。

authentication.service.ts:

import { Injectable } from '@angular/core';
import { AngularFire, AuthProviders, AuthMethods } from 'angularfire2';

@Injectable()
export class AuthService {
  private userModel= this.af.database.object('/users');
  constructor(private af: AngularFire) {
    this.af.auth.subscribe((auth) => {
      console.log(auth);
      this.userModel.set({
        uid: auth.uid,
        firstName: auth.displayName.split(0, auth.displayName.lastIndexOf(' ')),
        lastName: auth.displayName.split(auth.displayName.lastIndexOf(' '), auth.displayName.length),
        displayPic: auth.photoURL,
        provider:auth.provider
      });
    });
  }

  public loginFacebook (): void {
    this.af.auth.login({
      provider: AuthProviders.Facebook,
      method: AuthMethods.Popup
    })
  }
}

如果需要任何进一步的信息,请告诉我。

最后,感谢你的光临。:)

答案#1

我查看了 GitHub 上的 angularfire2 源代码,并检查了 FirebaseAuthState 接口,你可以在这里找到它。你可以看到 TypeScript 接口本身没有一个名为 'displayName' 的属性。然而,它确实显示有一些可为空的类型,似乎持有你正在寻找的数据。

export interface FirebaseAuthState {
  uid: string;
  provider: AuthProviders;
  auth: firebase.User;
  expires?: number;
  github?: CommonOAuthCredential;
  google?: GoogleCredential;
  twitter?: TwitterCredential;
  facebook?: CommonOAuthCredential;//<---based on your code I think this is what you're looking for.
  anonymous?: boolean;
}

我认为你会想更仔细地查看 auth.facebook 属性。为了更好地了解细节,我会简单地将你 subscribe 方法中的代码注释掉,然后将对象写入控制台,并使用浏览器开发者工具在浏览器中查看它。例如可以像这样。

this.af.auth.subscribe((auth) => {
  console.log(auth);
  //this.userModel.set({
    //uid: auth.uid,
    //firstName: auth.displayName.split(0, auth.displayName.lastIndexOf(' ')),
    //lastName: auth.displayName.split(auth.displayName.lastIndexOf(' '), auth.displayName.length),
    //displayPic: auth.photoURL,
    //provider:auth.provider
  //});
});

这将允许你更仔细地查看 auth.facebook 中的数据。