【问题标题】:Searching for a specific item in an Observable array在 Observable 数组中搜索特定项目
【发布时间】:2020-10-10 22:13:23
【问题描述】:

我正在尝试在 Observable 中搜索具有特定属性的项目。例如,对于用户列表,查找具有给定用户 ID 的用户。这是我的 component.ts 的相关部分:

import { Component, OnInit } from '@angular/core';
import { ContentService } from '../shared/services/content.service';
import { ActivatedRoute } from '@angular/router';
import { AngularFireModule } from '@angular/fire';
import { AngularFirestore, AngularFirestoreDocument  } from '@angular/fire/firestore';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-main',
  templateUrl: './main.component.html',
  styleUrls: ['./main.component.css']
})
export class MainComponent implements OnInit {
  main: Object;
  users: Observable<any[]>;
  
  constructor(private route: ActivatedRoute, private contentService: ContentService, private firestore: AngularFirestore, ) {}
  ngOnInit() {
    const pageData = this.route.snapshot.data['main'];
    this.main = this.contentService.pages[pageData];
      this.users = this.firestore.collection('users').valueChanges();
  }

  getOwner(id) {
    return this.users
      .map(users => users.find(user => user.uid.equals(id)));
  }

}

您可以看到我尝试尝试 this fix using map,但我收到错误消息“属性 'map' 在类型 'Observable' 上不存在”。任何帮助表示赞赏!

【问题讨论】:

    标签: javascript angular firebase


    【解决方案1】:

    尝试替换这个sintax

    export class MainComponent implements OnInit {
      main: Object;
      users: [];
      }
    
     getOwner(id): Observable<any> {
        return this.users
          .map(users => users.find(user => user.uid.equals(id)));
      }
    

    【讨论】:

      【解决方案2】:

      我认为你缺少pipe 函数

      return this.users.pipe(
            map(users => users.find(user => user.uid.equals(id)))
      )
      

      【讨论】:

      • 谢谢!这是可行的,但我在从返回的 Observable 获取属性时仍然遇到一些麻烦。我在@Simon Kazakov 的回答下的评论中有详细信息。
      【解决方案3】:

      如果您需要归还所有者,您应该这样做:

        getOwner(id) {
          return this.firestore.collection('users').get()
            .map(users => users.find(user => user.uid.equals(id)));
        }
      

      如果你想要一个可观察的,返回所有者,你应该这样做:

      owner$ = this.firestore.collection('users').valueChanges().pipe(
                map(users => users.find(user => user.uid.equals(id))));
      

      然后当你需要这个 observable 的值时,订阅它: 通过异步管道在模板中:

      [owner]="owner$ | async"
      

      或在组件类中:

      owner$.subscribe(o => console.log(o))
      

      【讨论】:

      • 谢谢,第二个选项主要为我工作!我唯一感到困惑的是对变量的赋值。对于上下文,我需要找到多个所有者,并且我在 HTML 中调用 getOwner 函数,就像这样(LoggedActivity 是另一个 Observable 我没有包含在原始问题中):&lt;tr *ngFor="let act of LoggedActivity | async"&gt; &lt;td&gt;{{getOwner(act.ownerId)}}&lt;/td&gt; &lt;/tr&gt; 那么我该怎么做调用getOwner后获取所有者的属性,例如displayName?
      猜你喜欢
      • 1970-01-01
      • 2010-10-09
      • 2012-05-01
      • 1970-01-01
      • 2012-10-25
      • 1970-01-01
      • 2013-11-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多