【问题标题】:What's The Proper Way To Combine Observable Data In Angular?在 Angular 中组合可观察数据的正确方法是什么?
【发布时间】:2020-12-18 12:36:44
【问题描述】:

我对 RxJS 和异步数据没有太多经验。我一直在嵌套订阅,感觉不对。我想知道组合或使用多个数据点的正确方法是什么,例如获取用户个人资料及其帖子。这是我目前拥有的:

  constructor(private storage: AngularFireStorage, private db: AngularFirestore, private route: ActivatedRoute) {
    // Get profile
    this.route.paramMap.subscribe(params => {
      const profileName = params.get('id');
      const username = db.doc<any>('usernames/' + profileName).valueChanges();
      username.subscribe(val => {
        this.user = db.doc<User>('users/' + val.user).valueChanges();
        this.user.subscribe(val => {
          const userPosts = this.db.collection<Post>('posts', ref => ref.where('user', '==', val.uid)).snapshotChanges();
          this.posts = userPosts.pipe(map(actions => actions.map(a => {
            const data = a.payload.doc.data() as Post;
            const mediaUrl = this.storage.ref('post/m/' + data.mediaM).getDownloadURL();
            const userData: Observable<User> = db.doc<User>('users/' + data.user).valueChanges();

            return {mediaUrl, userData, ...data}
          })))
        });
      });
    });
  }

【问题讨论】:

  • 不清楚你需要什么或什么不起作用
  • @Dalorzo 并不是说​​它不起作用;我不喜欢订阅嵌套在订阅中。我正在寻找更好或更合适的解决方案。

标签: angular typescript firebase google-cloud-firestore rxjs


【解决方案1】:

您可以使用 switchMap 将结果从一个 observable 传递到另一个 observable,这样您就不需要嵌套订阅。

this.route.paramMap.pipe(
  map(params => params.get('id')),
  switchMap(profileName => db.doc<any>('usernames/' + profileName).valueChanges()),
  switchMap(val => db.doc<User>('users/' + val.user).valueChanges()),
  switchMap(val => this.db.collection<Post>('posts', ref => ref.where('user', '==', val.uid)).snapshotChanges())
).subscribe(val => {});

【讨论】:

  • 这是一个干净的解决方案。它允许我使用 switch map 来获取配置文件数据,然后为帖子创建一个单独的变量。保持数据分离和可重复使用是一个优点。
猜你喜欢
  • 2019-04-30
  • 2011-01-04
  • 2022-01-10
  • 1970-01-01
  • 1970-01-01
  • 2018-10-10
  • 2021-12-06
  • 2010-09-15
  • 1970-01-01
相关资源
最近更新 更多