Angular 如何在没有订阅和嵌套观测的情况下从Firebase检索数据?

Angular 如何在没有订阅和嵌套观测的情况下从Firebase检索数据?,angular,firebase,firebase-realtime-database,angularfire,Angular,Firebase,Firebase Realtime Database,Angularfire,我在另一个Observable中有Observable,因此我必须使用嵌套的Observable.subscribes 是否有可能避免这种情况,在没有订阅的情况下从Firebase检索我的单用户数据?我用角火5 我的组件代码: export class UserAddEditComponent implements OnInit { userForm: FormGroup; userId: string; constructor(private route: Activate

我在另一个
Observable
中有
Observable
,因此我必须使用嵌套的
Observable.subscribes

是否有可能避免这种情况,在没有订阅的情况下从Firebase检索我的单用户数据?我用角火5

我的组件代码:

  export class UserAddEditComponent implements OnInit {

  userForm: FormGroup;
  userId: string;

  constructor(private route: ActivatedRoute, private usersService: UsersService) { }

  ngOnInit() {
    this.route.params.subscribe((params: Params) => {
      if (params['id']) {
        this.userId = params['id'];
        this.usersService.getUser(this.userId).subscribe((user) => {
          this.initForm(user);
        });
      } else {
        this.initForm();
      }
    });
  }
p.s.
getUser()
方法来自
UsersService
返回
可观察的

getUser(id:string):可观察{
返回这个.firebase.doc(`users/${id}`)。valueChanges();
}

您需要使用switchMap等待用户值

ngOnInit() {
  this.route.params.pipe(
    map(params => params['id']),
    switchMap(id => {
      // if there was an id we get the user, or else we return an observable with a value of null
      if (id) {
        return this.usersService.getUser(this.userId))
      }
      return Observable.of(null);
  )
  .subscribe((user?: User) => {
    // the user value will be either a user or null
    this.initForm(user);
  });
}
ngOnInit() {
  this.route.params.pipe(
    map(params => params['id']),
    switchMap(id => {
      // if there was an id we get the user, or else we return an observable with a value of null
      if (id) {
        return this.usersService.getUser(this.userId))
      }
      return Observable.of(null);
  )
  .subscribe((user?: User) => {
    // the user value will be either a user or null
    this.initForm(user);
  });
}