当我通过添加帖子组件添加新帖子时,它将帖子发布到我的仪表板组件。该组件包含所有通过dataService检索的帖子的概述。
但是...
每当执行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());
}
}
答案 0 :(得分:0)
您可以创建一个actionForSucess函数,并将类似这样的内容传递给您的订阅,以重定向到您的新创建。
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])
);
}
答案 1 :(得分:0)
将posts$
设置为吸气剂根本不起作用。它本身并没有发出任何值。您将需要其他方法来获取帖子。
为确保始终使用addNewPost()
方法发出帖子,您可以在发布之后映射响应并在主题上发出获取的帖子。但是,您也可以在收到addNewPost
方法的响应后在DashboardComponent中调用此方法(无需在fetchPosts
中预订PostDataService
)。