【问题标题】:How to convert generic type array to specialized type array in typescript如何在打字稿中将泛型类型数组转换为专用类型数组
【发布时间】:2021-12-29 09:01:20
【问题描述】:

我在我的应用程序中使用了 firebase。因此,firebase 的 snapshotChanges() 方法返回一个 SnapshotAction 数组类型的 Observable,我想在订阅 Observable 后将其转换为特定类型的数组。那么,我们如何在 typescript 中做到这一点呢?

查看下面的代码库以更好地理解它,

// Below observable is returned by firebase snapshotChanges() method 
Observable<SnapshotAction<Product>[]>

// Now, after I subscribe to the above observable I get below type,
SnapshotAction<Product>[]

// Now I want to convert "SnapshotAction<Product>[]" to "Product[]" in typescript

【问题讨论】:

  • Rupesh,如果您对我的回答感到满意,请更新/接受答案,这样我就可以获得一些神奇的互联网积分。
  • 马特,我已经通过单击您答案旁边的向上箭头给出了我的反馈。但是,我看不到任何接受或更新的选项。
  • 另外,我的反馈已经被堆栈溢出记录了,但我至少需要 15 分才能在这里投票,我相信我会尽快实现。

标签: angular typescript firebase


【解决方案1】:

快照操作有一个有效负载字段,它将为您提供一个

DatabaseSnapshot<Product>

DatabaseSnapshot 有一个 val() 方法,该方法将根据快照是否存在返回 Product 或 null。所以你可以写一个这样的小函数来提取产品:

function example(input: SnapshotAction<string>[]): (string | null)[] {
    return input.map(action => action.payload.val())
}

注意这是返回字符串 | null 因为快照可能不存在。你可以看看

action.payload.exists()

如果您想进行额外的检查或过滤。

【讨论】:

  • 感谢@matt helliwell,您对我的查询的帮助确实帮助我实现了我想要的代码库。我使用 map() 遍历每个 SnapshotAction[ ] 数组,并使用 product.payload.val() 方法提取 Product json 并将其推送到 Product[] 数组中,这是我的最终目标。
【解决方案2】:

所以,我最终通过映射 SnapshotActionSnapshotAction[ ] 数组转换为更具体的类型 Product[ ] > 并从中提取 Product 类型的有效负载(json)值,然后将其推送到我在下面代码的第一行中声明的 Product[] 中。

products: Product[] = [];

this.productService.getAll().pipe(
      switchMap((products: SnapshotAction<Product>[]) => {
      
        // Our intention starts here
        products.map((product: SnapshotAction<Product>) => {
          let prod: Product = product.payload.val();
          prod.key = product.key;
          
          this.products.push(prod);
        });
        
      });
    );
Final Outcome: 
[
      {category: 'bread', imageUrl: 'img1_url.jpg', price: 3, title: 'Freshly Baked Bread', key: '-MrS7JBEldfwCbmGSCBY'},
      {category: 'fruits', imageUrl: 'img2_url.jpg', price: 234, title: 'Orange', key: '-MrSweHxR168xz3lyxm1'},
      {category: 'vegetables', imageUrl: 'img3_url.jpg', price: 2.22, title: 'Spinach', key: '-MrTBTEe4sXK3Hh31Fui'}
]

【讨论】:

  • 也许可以检查一下如何通过代码而不是解释、上下文等来稍微改进这个答案。
  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
  • nilsandrey,我希望现在答案更清楚了。
猜你喜欢
  • 2022-01-21
  • 1970-01-01
  • 2022-10-14
  • 1970-01-01
  • 2020-02-05
  • 1970-01-01
  • 2021-02-14
  • 2021-12-01
  • 2022-10-22
相关资源
最近更新 更多