【问题标题】:Angular Observable list preproccessAngular Observable 列表预处理
【发布时间】:2022-01-02 16:31:46
【问题描述】:

我有一个 Angular12 应用程序,我使用 AngularFire 从 Firebase 实时数据库获取数据。因为我需要在我的代码中的不同位置使用我的数据,所以我希望我的 DAO 服务能够获取 firebase Observable 列表,并在其中进行少量预处理(将字符串日期转换为 Date 对象)。如果我执行此预处理,那么我将失去订阅能力,现在我的应用程序无法获得实时数据的好处。所以我想让那个预处理返回一个 Observable 列表,但我不知道怎么做。

我的代码:

FantaroiDAOService

  private list = this.db.list<Fantaros>('fantaroi')

  constructor(private db: AngularFireDatabase){}

  public getIpir() {
    return this.list.valueChanges();
  }

应用组件

  ngOnInit(): void {
    let fantaroi: Fantaros[] = [];
    this.dao.getIpir().subscribe(f => {
      fantaroi = f.map(f => {
        const soc = f.soc.map(date => new Date(date))
        const dishes = f.dishes? f.dishes.map(date => new Date(date)) : []
        const off = f.off.map(date => new Date(date))
        return new Fantaros(f.name, soc, dishes, off);
      })
// other Component related code.
});
}

fantaroi 是我要监视更改然后使用它来更新我的视图的列表。有没有办法做到这一点?或者我是否必须在使用该列表的每个位置复制粘贴解析到 Date 对象的代码?

【问题讨论】:

    标签: angular typescript web observable


    【解决方案1】:

    您应该能够使用pipe 并使用map 运算符应用转换:

    public getIpir() {
      return this.list.valueChanges().pipe(
        map(fantaroi => fantaroi.map(f => {
          const soc = f.soc.map(date => new Date(date))
          const dishes = f.dishes? f.dishes.map(date => new Date(date)) : []
          const off = f.off.map(date => new Date(date))
          return new Fantaros(f.name, soc, dishes, off);
        })
      );
    }
    
    

    【讨论】:

    • 哦,这就是pipe的使用方法。非常感谢!
    猜你喜欢
    • 2020-12-21
    • 1970-01-01
    • 1970-01-01
    • 2018-08-06
    • 1970-01-01
    • 2017-03-10
    • 2020-10-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多