Angular 2向组件发送回调服务

时间:2017-03-08 10:02:59

标签: angular facebook-graph-api firebase service angularfire2

大家好,我几个小时都在搜索,尝试过BehaviorSubject or ReplaySubeEvents等所有内容,但不成功...

问题

我有一个个人资料页面,其中有一个按钮loginFb(),它调用我的users.services。这个服务用FacebookAPI调用数据并将它们发送到数据库..现在发回一个"回调"使用用户对象:)

添加到我的组件

因为当我(点击)登录时,我在Firebase中看到了新用户,但我的页面没有刷新",我认为这是因为我的异步太迟了......?

这是我的个人资料。(ProfilePage)

import { Users } from '../../services/users.service';

export class ProfilePage {
    user :any;
    isConnected :boolean = false;

  constructor(public navCtrl: NavController, 
              public usersService: Users, 
              public modalCtrl: ModalController) { }

  loginFB(){
    this.usersService.registerUserFb();
    this.usersService.getUserFacebook().subscribe((userObject) => {
       this.user = userObject;
      })
    }
}

这是我的users.services.ts

  getUserFacebookId(){
   Facebook.getLoginStatus().then((response) => {
     alert("id in getUSERFACEBOOKID = " + JSON.stringify(response.authResponse.userID));
      return response.authResponse.userID;
    });
  }

  getUserFacebook(){
    return this.af.database.object('users/' + this.getUserFacebookId());
  }

registerUserFb(){
    Facebook.login(['email']).then((response) => {
      Facebook.getLoginStatus().then((response) => {
        if(response.status == 'connected'){
          this.checkIfUserExists(response.authResponse.userID);
         }

        });
      });
  }

checkIfUserExists(uid) {
    let user = this.af.database.object('users/' + uid, { preserveSnapshot: true });
    user.subscribe(snapshot => {
    if(!snapshot.exists()) {
      this.saveInDatabase(uid);
    }
    });
}

saveInDatabase(uid){
      Facebook.api('/' + uid + 
              '?fields=id, name, ...])
            .then((data) => {
                var newUser = {
                  //data saving
                };
                this.af.database.object('users/' + uid).set(newUser);
                this.showToast("User successfully registered");
    });
  }

2 个答案:

答案 0 :(得分:2)

您发送多个异步请求,您必须等到$total = 5; $mike = rand(1,$total-2); // so that max value is 3 (everyone should get at least 1) ($total - $numberOfVarsToDistributeTheValueTo + 1) $ralf = rand(1,$total - $mike - 1); // if 3 goes to mike, only 1 goes to ralf $ashley = $total - $mike - $ralf; // i hope you understand. // use it. 结算,然后致电registerUserFb

getUserFacebook

答案 1 :(得分:0)

这里有一些关于它应该如何使用RxJs的伪代码:

registerUserFb():Observable<any>{
    return Facebook.login(['email']).flatMap(() => this.getLoginStatus());
}

getLoginStatus():Observable<any>{
    return Facebook.getLoginStatus();
}

loginFb(){
    this.registerUserFb().flatMap(()=>this.usersService.getUserFacebook()).subscribe((userObject=>{

    }))
}

正如@ssougnez所指出的,两个异步调用之间存在竞争。