使用数据存储和主题行为时更新回调(Angular 7)

时间:2018-11-30 08:09:27

标签: angular typescript rxjs angular7

第一篇文章。我对Angular很陌生。我已经对此进行了一些搜索,但是没有找到答案。

在我直接订阅与API联系并返回值的get / post / put函数之前。这样做时,我可以直接在GUI中处理回调。

这种方法不是最佳方法,因为我需要在多个组件之间共享数据。

我最终创建了数据存储。现在的问题是,在执行例如:update()之后,我仍然需要回调。

我该如何实现?

谢谢!

在使用中:

private _projects: BehaviorSubject<Project[]>; 
private serviceUrl = `${this.baseUrl}/api/project`;

private dataStore: { 
    projects: Project[]
};

get projects() {
    return this._projects.asObservable();
}

constructor(private http: HttpClient, public listener: ProjectListenerService, public authService: AuthService) {
    super();

    this.dataStore = { projects: [] };
    this._projects = <BehaviorSubject<Project[]>>new BehaviorSubject([]);
}

public loadAll() {
    return this.http.get<Project[]>(this.serviceUrl).pipe(
        catchError(this.handleError),
        map(res => res.map(v => new Project(v)))
    ).subscribe(data => {
        this.dataStore.projects = data;
        this._projects.next(Object.assign({}, this.dataStore).projects);
    }, error => console.log('Could not load projects.'));
}

public update(project: Project) {
    let payLoad = { Data: project, ConnectionId: this.listener.ClientConnectionId, HubAction: "AllExcept" };

    this.http.put(`${this.baseUrl}/${project.id}`, payLoad).subscribe(data => {
      if (typeof data == typeof true) {
        this.dataStore.projects.forEach((t, i) => {
          if (t.id === project.id) { this.dataStore.projects[i] = project; }
        });

        this._projects.next(Object.assign({}, this.dataStore).projects);
      } else console.log('Could not update project.');
    }, error => console.log('Could not update project.'));
}

在组件中:

this.projectService.loadAll();

//Here i update a project, but i want to be able to do things after the update, like updating GUI. 
this.projectService.update(project);

//What i want to do... 
this.projectService.update(project).subscribe(data=>{
 //Do some gui stuff, do another update etc etc..
});

this.projectService.update(project).then()... etc

1 个答案:

答案 0 :(得分:1)

我认为最简单的方法是向update添加另一个参数,该参数将是您在this._projects.next之后调用的回调。

更多的“ Rx”解决方案将使用share()shareReplay()并返回共享的Observable。

public update(project: Project) {
  const shared = this.http.put(...).pipe(
    shareReplay(),
  );

  shared.subscribe(data => {
    ...
  });

  return shared;
}

然后,您可以订阅返回的Observable并根据需要更新GUI。

this.projectService.update(project).subscribe(...);