【问题标题】:How to retrieve data from Firebase without subscription and nested Observables?如何在没有订阅和嵌套 Observables 的情况下从 Firebase 检索数据?
【发布时间】:2018-08-14 23:29:21
【问题描述】:

我在另一个Observable<Params[]> 中有Observable<User>,所以我必须使用嵌套的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();
      }
    });
  }

附:来自UsersServicegetUser() 方法返回Observable<User>

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

【问题讨论】:

    标签: angular firebase firebase-realtime-database angularfire


    【解决方案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);
      });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-25
      • 2022-01-24
      • 1970-01-01
      • 2014-04-17
      • 1970-01-01
      • 2017-08-10
      • 2018-02-12
      • 2016-10-27
      相关资源
      最近更新 更多