【发布时间】:2021-04-28 11:20:33
【问题描述】:
我创建了两个 Angular 组件:一个用于创建新帖子,一个用于显示所有帖子。在我按下创建帖子的按钮后,我被重定向到我的 PostList 组件,其中显示了我的所有帖子。我用了window.location.href,这样PostList页面可以自动重新加载,这样新帖子就出现了,不需要手动刷新。问题是它很慢,实际上需要两次刷新,一次在创建帖子时,一次在刷新帖子列表时。有没有更快的方法来导航到帖子列表并显示新帖子而无需手动刷新页面?如果我使用router.navigateByUrl('/posts'),我必须手动刷新页面以显示新帖子,这是不希望的。
export class PostCreateComponent implements OnInit {
model: any = {};
@Output() newContent = new EventEmitter();
publishNewPost() {
this.postService.createPost(this.model).subscribe(newPost => {
this.model = newPost;
this.newContent.emit(model);
this.router.navigateByUrl('/posts');
});
}
}
export class PostListComponent implements OnInit {
posts: Post[];
pagination: Pagination;
postParams: PostParams = new PostParams();
ngOnInit(): void {
this.loadPosts();
}
loadPosts() {
this.postService.getPosts(this.postParams).subscribe(posts=> {
this.posts = posts.result;
this.pagination = posts.pagination;
});
}
addNewContent(content: Post) { this.posts.push(content) }
}
用于创建帖子:
<form #postForm="ngForm" (ngSubmit)="createPost(this.model)" autocomplete="off">
</form>
帖子列表:
<div class=" container mt-3" >
<span *ngFor="let post of posts">
<app-post-card (newContent)="addNewContent($event)"
[post]="post" class="item" ></app-post-card>
</span>
</div>
邮政服务:
getPosts(postParams: PostParams) {
var response = this.postCache.get(Object.values(postParams).join('-'));
if (response) {
return of(response);
}
let params = this.getPaginationHeaders(postParams.pageNumber, postParams.pageSize);
params = params.append('orderBy', postParams.orderBy);
return this.getPaginatedResult<Post[]>(this.baseUrl + 'posts', params)
.pipe(map(response => {
this.postCache.set(Object.values(postParams).join('-'), response);
return response;
}));
}
createPost(model: any) {
return this.http.post<Post>(this.baseUrl + 'posts/create', model);
}
【问题讨论】:
-
您可以使用@Output 并在创建一个时将您的帖子推送到父组件中的帖子数组中,第二个选项是让 rxjs 主题,在父组件中订阅它,当有变化时,您只需调用 this.posts.push(change) 并在提交帖子时在您的子组件中执行 this.subject.next(post)
-
我尝试过使用@Output,但可能不行,因为它不起作用。我已经更新了我的答案。
-
<app-post-card (newContent)="addNewContent($event)...>和你的 ts 文件addNewContent(content) { this.posts.push(content) },你不需要对你的loadPosts()函数做任何事情 -
好的,所以我已将 addNewContent(content) 添加到问题中的代码中,但它仍然不起作用。 publishNewPost() 的代码可以吗?还是我错过了什么?
-
看起来不错,您的后端返回插入的帖子吗?在您的
publishNewPost()中尝试console.log(newPost)以查看您发布的帖子是否从后端返回...如果不是,那么您必须删除this.model = newPost