我的应用程序有不同的部分(我使用独立组件,所以不想说模块)。我不想在部分之间有直接的依赖关系。
现在,其中一个部分是搜索。 当用户进行搜索时,可以显示不同的搜索结果类型。 假设
searchResultType1, searchResultType2, searchResultType3
(它们是搜索结果项组件)。所有这些都可以同时混合显示在列表中。它们在模板中使用 ngFor
显示。
每个
searchResultTypeX
都在应用程序的相应部分中实现。
我正在考虑定义所有
searchResultX
类型实现的抽象类,但它们都作为抽象类注入到搜索组件中。
当我有一个时,我知道如何实现这一点,但无法弄清楚是否有一种方法可以根据搜索返回的数据类型注入所有这些。
所以你有三种类型,输出可以是这些类型属性的组合。
确保您拥有的每种类型都将
?:
添加到属性中。这样您就可以合并所有三种类型,但不必定义合并类型的所有属性!
export interface searchResultType1 {
test1?: string;
test2?: string;
test3?: string;
}
...
对所有类型执行此操作,现在创建一个通用类型
searchResultTypeX
包含 &
运算符,以便所有属性都存在于单一类型中。
export type searchResultTypeX = searchResultType1 & searchResultType2 & searchResultType3;
现在您可以将
searchResultTypeX
设置为合并属性的返回类型
当您使用 HTML 时。您可以使用函数将类型设置为
searchResultType1
或 searchResultType2
或 searchResultType3
,以便在需要时保留输入!
isSearchResultType3(value: searchResultTypeX): searchResultType3 {
return value as searchResultType3;
}
html
@if(isSearchResultType3(item); as itemTyped) {
<!-- some html code which uses the typed item -->
}