0

我在显示我的 component.ts 文件中的“displayName”属性时遇到问题(用于在 console.log 中进行测试),但它在模板中运行良好。

组件.ts:

 constructor(
    private fb: FormBuilder,
    private auth: AuthService
  ) { }
  ngOnInit() {
    this.buildForm();
    console.log(this.auth.user.displayName); // this line is the problem
  }

但是,这在模板中可以正常工作:

组件.html

{{ user.displayName }}

如果您需要有关服务的更多详细信息...

auth.service.ts

export class AuthService {

  user: Observable<User>;

  constructor(
    private afAuth: AngularFireAuth,
    private afs: AngularFirestore,
  ) {
    //// Get auth data, then get firestore user document || null
    this.user = this.afAuth.authState.pipe(
      switchMap(user => {
        if (user) {
          return this.afs.doc<User>(`users/${user.uid}`).valueChanges();
        } else {
          return of(null);
        }
      })
    );
  }
4

1 回答 1

0

我必须订阅 observable。

this.auth.user.subscribe(user => {
  this.userForm.get('email').setValue(user.email);
  this.userForm.get('displayName').setValue(user.displayName);
});
于 2019-08-18T04:10:08.883 回答