使用Angular2在Firebase中获取提供者UID

时间:2017-09-01 09:53:24

标签: facebook angular firebase facebook-graph-api firebase-authentication

我试图使用Angular2中的firebase提供程序访问facebook uid,但我无法从facebook提供程序获取用户uid。

当我使用authState.uid它向我显示firebase uid而不是facebook uid,文档已过时且authState.facebook.uid已弃用,因此我不知道获取facebook用户ID的正确方法。

通过互联网我看到这是一种使用authState.providerData.uid获取facebook用户ID的新方法,但在控制台中我得到了未定义。

这是我的代码:

export class AppComponent {
  user: Observable<firebase.User>;
  displayName;
  photoURL;


  constructor(public afAuth: AngularFireAuth, private db: AngularFireDatabase, private http: Http) {
    this.user = afAuth.authState;
  }

  ngOnInit() {
    this.afAuth.authState.subscribe(authState => {
      if (!authState) {
        console.log('NOT LOGGED IN');
        this.displayName = null;
        this.photoURL = null;
        return;
      }
      let userRef = this.db.object('/users/' + authState.uid)
      userRef.subscribe(user => {
        let url = `https://graph.facebook.com/v2.8/${authState.uid}?fields=first_name,last_name&access_token=${user.accessToken}`;
        this.http.get(url).subscribe(response => {
          let user = response.json();
          userRef.update({
            firstName: user.first_name,
            lastName: user.last_name
          });
        });
      });


        this.displayName = authState.displayName;
        this.photoURL = authState.photoURL;
        console.log(authState.uid);
    });
  }

感谢您的时间和帮助:)

1 个答案:

答案 0 :(得分:0)

好的,所以我解决了这个问题,我不知道这是不是最好的方法,但它对我有用......

要获取Facebook uid而不是使用authState.facebook.uid(我认为这已被弃用)我现在正在使用authState.providerData [0] .uid

我尝试过使用authState.providerData.uid,但它没有用,所以我把[0]放进了数组并获取了uid。