使用TypeScript和Angular,我创建了以下可观察到的HTTP订阅:
this.movie.getByKeywordIDChrono().subscribe((data: {
page: number,
results: object[],
total_pages: number,
total_results: number
}) => {
if (data.total_pages > 1) {
for (let i = 2; i <= data.total_pages; i++) {
this.movie.getByKeywordIDChronoNextPage(i).subscribe((data: {
page: number,
results: object[],
total_pages: number,
total_results: number
}) => {
...
})
}
}
})
两个预订的data
对象具有相同的类型。
在两个实例中如何使用为data参数创建的类型?
答案 0 :(得分:1)
使用接口或类型别名:
type MyData = { // type alias
page: number,
results: object[],
total_pages: number,
total_results: number
}
this.movie.getByKeywordIDChrono().subscribe((data: MyData) => {
if (data.total_pages > 1) {
for (let i = 2; i <= data.total_pages; i++) {
this.movie.getByKeywordIDChronoNextPage(i).subscribe((data: MyData) => {
...
})
}
}
})
或类似的界面:
interface MyData {
page: number,
results: object[],
total_pages: number,
total_results: number
}