angular2-jsonapi icon indicating copy to clipboard operation
angular2-jsonapi copied to clipboard

Observable store

Open monkeycatdog opened this issue 6 years ago • 1 comments

Hello. I think it would be very convenient to add the ability to subscribe to changes in the current state of the store.

For example, there is a method peekAll, it would not be bad to have a similar method returning Observable type.

What do you think?

monkeycatdog avatar Apr 08 '19 16:04 monkeycatdog

Simple implementation of my thinks

@Injectable({
  providedIn: 'root'
})
@JsonApiDatastoreConfig(config)
export class DataStoreService extends JsonApiDatastore {
  private subjects = new Map<ModelType<any>, BehaviorSubject<any>>();

  constructor(http: HttpClient) {
    super(http);
  }

  private createStoreForTypeIfNotExist<T extends JsonApiModel>(modelType: ModelType<T>) {
    if (!this.subjects.has(modelType)) {
      this.subjects.set(modelType, new BehaviorSubject(this.peekAll(modelType)));
    }
  }

  findAll<T extends JsonApiModel>(
    modelType: ModelType<T>,
    params?: any,
    headers?: HttpHeaders,
    customUrl?: string
  ): Observable<JsonApiQueryData<T>> {
    return super.findAll(modelType, params, headers, customUrl).pipe(
      tap(() => {
        this.createStoreForTypeIfNotExist(modelType);
        this.subjects.get(modelType).next(this.peekAll(modelType));
      })
    );
  }

  peekAllPipe<T extends JsonApiModel>(modelType: ModelType<T>): BehaviorSubject<T[]> {
    this.createStoreForTypeIfNotExist(modelType);

    return this.subjects.get(modelType);
  }
}

monkeycatdog avatar Apr 09 '19 08:04 monkeycatdog