如何从Firebase中获取没有订阅和嵌套Observable的数据?

时间:2018-08-14 10:26:16

标签: angular firebase firebase-realtime-database angularfire

我在另一个Observable<User>中有Observable<Params[]>,因此我必须使用嵌套的Observable.subscribes

是否可以避免这种情况并从Firebase中检索我的单个用户数据而无需订阅?我使用AngularFire 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方法返回Observable<User>

  getUser (id: string): Observable<User> {
    return this.firebase.doc<User>(`users/${id}`).valueChanges();
  }

1 个答案:

答案 0 :(得分:1)

您需要使用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);
  });
}