【问题标题】:Angular: I need to refresh after using CRUDAngular:使用 CRUD 后我需要刷新
【发布时间】:2019-05-22 08:41:03
【问题描述】:

当我通过我的 add-post 组件添加新帖子时,它会将帖子发送到我的仪表板组件。该组件包含所有帖子的概述,通过 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());
  }
}

【问题讨论】:

    标签: typescript observable angular7


    【解决方案1】:

    您可以创建一个 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])
      );
    }
    

    【讨论】:

    • 在您的情况下,您需要在构造函数上添加路由器。 “私有路由器:路由器”。
    【解决方案2】:

    posts$ 设置为getter 根本不起作用。它本身不会发出任何值。您将需要其他方法来获取帖子。

    为确保您始终在addNewPost() 方法之后发布帖子,您可以在发布后映射响应并在您的主题上发布获取的帖子。但是,您也可以在收到addNewPost 方法的响应后在 DashboardComponent 中调用此方法(无需在您的PostDataService 中订阅fetchPosts)。

    这是一个例子:https://stackblitz.com/edit/angular-kx4cco

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-19
      • 2018-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-01
      • 2021-07-02
      • 2020-07-04
      相关资源
      最近更新 更多