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

Update callback when using datastore and subject behaviour (Angular 7)

首先post。我对 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

我认为最简单的方法是向 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(...);