嗨,我使用 angular 和 ngrx。我用ngrx制作动态表。如果数组中有 10 个数据,我想每页显示 2 个项目。当我访问组件时,调用服务器并获取 2 个项目。然后如果我单击下一步按钮,它将调用服务器以获取新的 2 个项目。但是在我的代码中,当我再获得 2 个新项目时,组件会在第二页显示 4 个项目。如果我点击最后一页,这意味着我得到了所有 10 的数据,分页运行良好。我不知道是什么问题
Image.component.html
<div
class="row card-margin"
*ngFor="
let image of images
| paginate
: {
itemsPerPage: itemPerPage,
currentPage: p,
totalItems: imageCounts
};
let i = index
"
[routerLink]="['/admin/image', image.id]"
>
<div class="text-center mt-3">
<pagination-controls
(click)="absoluteIndex(p - 1)"
(pageChange)="p = $event"
></pagination-controls>
</div>
Image.component.ts
export class ImageComponent implements OnInit {
images: Image[] = [];
p: number = 1; // current page for pagination
itemPerPage = 2;
users: User[] = [];
imageCounts: number = 10;
constructor(
private store: Store<fromApp.AppState>
) {}
ngOnInit(): void {
this.getImagesSubscription = this.store
.select("images")
.pipe(map((imagesState) => imagesState.images))
.subscribe((images: any) => {
this.images = images;
});
}
absoluteIndex(indexOnPage: number) {
let newIndex = 2 * indexOnPage;
if (indexOnPage >= this.images.length / 2) {
this.store.dispatch(
new ImagesActions.AddImagesIndex({
indexNum: newIndex,
imageLength: this.images.length,
})
);
} else {
console.log("nothing to do");
}
}
}
Image.reducer.ts
import { Image } from "../../../Image/models/image.model";
import * as ImagesActions from "./images.action";
export interface State {
images: Image[];
}
const initialState: State = {
images: [],
};
export function imagesReducer(
state = initialState,
action: ImagesActions.ImagesActions
) {
switch (action.type) {
case ImagesActions.GET_IMAGES:
return {
...state,
images: [...action.payload["images"]],
};
case ImagesActions.ADD_IMAGES:
return {
...state,
images: [...state.images, ...action.payload["images"]],
};
default:
return state;
}
}
图像效果.ts
fetchImages$ = createEffect(
() => {
return this.actions$.pipe(
ofType(ImagesActions.FETCH_IMAGES),
map((action: ImagesActions.FetchImages) => action.payload),
switchMap((indexNum) => {
console.log(indexNum);
let body = {
number: indexNum,
};
return this.http.post<Image[]>(this.globalUrl + "/admin/image", body);
}),
map((images) => {
return {
...(images ? images : []),
};
}),
map((images) => {
return new ImagesActions.GetImages(images);
})
);
}
);
addImages$ = createEffect(() => {
return this.actions$.pipe(
ofType(ImagesActions.ADD_IMAGES_INDEX),
map((action: ImagesActions.AddImages) => action.payload),
switchMap((indexNum) => {
const body = {
number: indexNum,
};
return this.http.post<Image[]>(this.globalUrl + "/admin/image", body);
}),
map((images) => {
return {
...images,
};
}),
map((images) => {
return new ImagesActions.AddImages(images);
})
);
});