为什么我无法保存从firebase服务获得的数据

时间:2017-04-06 00:18:17

标签: angular firebase angularfire2

Component.ts

  ngOnInit() {        
      this.profileService.getBasicProfile(this.uid).subscribe(
        basic => {
          console.log(basic);   //line 1
          this.usedBasicProfile = basic;
          console.log(this.usedBasicProfile);   //line 2
        }  
      )
      console.log(this.usedBasicProfile);  //line 3
}

Service.ts

    savedBasicProfile: FirebaseObjectObservable<UserBasic>;

getBasicProfile(uid: string) {
    this.savedBasicProfile = this.af.database.object('/users/user'+uid);
    console.log(this.savedBasicProfile);
    return this.savedBasicProfile;
}

第1行和第2行的console.log正常工作,但第3行输出未定义。 任何帮助将不胜感激。

///////////////////////////修改

  constructor(
  private authService: AuthGuard,
  private profileService: ProfileService
) 
{
  this.uid = this.authService.getUid();      
  console.log(this.uid);

  this.profileService.getBasicProfile(this.uid).subscribe(
    basic => {
      this.usedBasicProfile = basic;  //how to make this line work?
    }  
  );
  console.log(this.usedBasicProfile);
}  

1 个答案:

答案 0 :(得分:0)

您应该了解Observables中涉及的异步过程。

ngOnInit() {        
      this.profileService.getBasicProfile(this.uid) executed
      console.log(this.usedBasicProfile);  //line 3  executed
}

首先进行服务调用并执行第3行。 返回数据时,只会触发订阅,此时您将获得值

.subscribe( ///called  only when the data is returned
            basic => {
              console.log(basic);   //line 1 executed
              this.usedBasicProfile = basic;
              console.log(this.usedBasicProfile);   //line 2
            }