typescript - Angular:使用 CRUD 后我需要刷新
问题描述
当我通过我的 add-post 组件添加新帖子时,它会将帖子发送到我的仪表板组件。该组件包含通过数据服务检索的所有帖子的概述。
然而...
每当我执行 CRUD 操作时,我都需要刷新页面以查看更改。我认为这与 Observables 有关。我想我正确地使用了它们,但它们似乎不起作用。
export class DashboardComponent {
public filterPostTitle: string;
public filterPost$ = new Subject<string>();
private _fetchPosts$: Observable<Post[]> = this._postDataService.posts$;
public loadingError$ = this._postDataService.loadingError$;
showAddPost = false;
constructor(private router: Router, private _postDataService: PostDataService) {
this.filterPost$.pipe(
distinctUntilChanged(),
debounceTime(300),
map(val => val.toLowerCase())
).subscribe(val => (this.filterPostTitle = val));
}
toggleAddPost(): void {
this.showAddPost = !this.showAddPost;
}
get posts$(): Observable<Post[]> {
return this._fetchPosts$;
}
applyFilter(filter: string) {
this.filterPostTitle = filter;
}
addNewPost(post) {
this._postDataService.addNewPost(post).subscribe();
}
@Injectable({
providedIn: 'root'
})
export class PostDataService {
public loadingError$ = new Subject<string>();
public $postsChange = new Subject<any>();
constructor(private http: HttpClient) { }
get posts$(): Observable<Post[]> {
return this.http.get(`${environment.apiUrl}/posts/`).pipe(catchError(error => {
this.loadingError$.next(error.statusText);
return of(null);
}),
map((list: any[]): Post[] => list.map(Post.fromJSON)),
share()
);
}
addNewPost(post: Post) {
return this.http.post(`${environment.apiUrl}/posts/`, post.toJSON());
}
}
解决方案
您可以创建一个 actionsForSucess 函数并将类似这样的内容传递给您的订阅,以重定向到您的新创建。
addNewPost(post) {
this._postDataService.addNewPost(post).subscribe(
post => actionsForSuccess(post)
);
}
private actionsForSuccess(post: Post) {
this.router.navigateByUrl('posts', { skipLocationChange: true })
.then(
() => this.router.navigate(['posts', 'edit', post.id])
);
}