angular - 在 Angular 中重新路由后重新加载数据
问题描述
我创建了两个独立的 Angular 组件:PostList 和 PostCreate。PostCreate 用于创建新帖子,PostList 用于从数据库中检索帖子并显示所有帖子。在我按下在 PostCreateComponent 中创建帖子的按钮后,我被重定向到我的 PostList 组件,我希望看到显示的新帖子,而无需手动刷新页面。我已经尝试过window.location.reload()
了,它确实可以工作,但是速度很慢并且会进行两次刷新。我可以让这更快吗?我也尝试过使用@Output
,但它不起作用,因为 PostCreateComponent 不是 PostListComponent 的子组件。这是 PostCreateComponent:
import { Component, OnInit, Output } from '@angular/core';
import { Router } from '@angular/router';
import { Subscription } from 'rxjs';
import { Pagination } from 'src/app/_models/pagination';
import { Post } from 'src/app/_models/post';
@Component({
selector: 'app-post-create',
templateUrl: './post-create.component.html',
styleUrls: ['./post-create.component.css']
})
export class PostCreateComponent implements OnInit, OnDestroy {
model: any = {};
constructor(private postService: PostsService, private router: Router) { }
ngOnInit(): void {
}
createPost(model: any) {
this.postService.createPost(model).subscribe(post => {
this.model = post;
this.router.navigateByUrl('/posts')
.then(() => {
window.location.reload();
});
}, error => {
console.log(error);
this.toastr.error(error.error);
});
}
}
<form #postForm="ngForm" (ngSubmit)="createPost(this.model)" autocomplete="off">
<div class="form-group">
<input class="title form-control" name="title" [(ngModel)]="model.heading">
</div>
<div class="form-group">
<textarea class="form-control" name="text" [(ngModel)]="model.body">
</textarea>
</div>
<div class="form-group">
<button type="submit" class="btn">Post</button>
</div>
</form>
这是 PostListComponent:
import { Component, Input, OnInit } from '@angular/core';
import { Pagination } from 'src/app/_models/pagination';
import { Post } from 'src/app/_models/post';
import { PostParams } from 'src/app/_models/postParams';
import { PostsService } from 'src/app/_services/posts.service';
@Component({
selector: 'app-post-list',
templateUrl: './post-list.component.html',
styleUrls: ['./post-list.component.css']
})
export class PostListComponent implements OnInit {
posts: Post[];
pagination: Pagination;
postParams: PostParams = new PostParams();
constructor(private postService: PostsService) { }
ngOnInit(): void {
this.loadPosts();
}
loadPosts() {
this.postService.getPosts(this.postParams).subscribe(response => {
this.posts = response.result;
this.pagination = response.pagination;
});
}
}
<div class=" container mt-3" >
<span *ngFor="let post of posts">
<app-post-card [post]="post" class="item" ></app-post-card>
</span>
</div>
解决方案
推荐阅读
- ios - 自定义布局 1 大 2 小单元 UICollectionView
- dax - DAX Power Pivot: "= CONCATENATEX(CALCULATETABLE(" 如何避免重复?
- excel - 从多个工作簿中检索数据,都在同一个选定文件夹中?
- android - 如何摆脱 Hilt 的循环编译错误?
- python - 相关字段查找无效:用户
- kubernetes - Kubernetes 中的嵌入式 Hazelcast 不形成集群
- eclipse - 我想创建一个我的世界客户端
- css - 用 SVG 创建图标按钮的“最佳实践”方法是什么?
- google-bigquery - Big Query:发生内部错误,无法完成请求
- visual-studio - 适用于 Windows Embedded Compact 7 的 Platform Builder 与 Visual Studio 的兼容性