Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

subscribe observable (as subject)

i have following example code which returns id+1 of it’s elements:

EntitiesService:

  public create(model: Model): Observable<number> {
        var subject = new Subject<number>();
        this.GetAll().subscribe(result => {
            if (result.find(x => x.name == model.name)) {
                return;
            }
            model.id = result[result.length - 1].id + 1;
            EntitiesService.mock.push(model);
            subject.next(model.id);
        })
        return subject.asObservable();
    }

and i would like to subscribe it to get last id:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

component:

 createMealType(type: string) {
    return this.EntitiesService.create({
      name: type
    }).subscribe((id) => {
      console.log(id);
    })}

but it never goes to console.log while im debugging neither dont do console.log

get all retyurns only of(mock)

  public GetAll(): Observable<Model[]> {

        return of(EntitiesService.mock);
    }

how should i handle it?

>Solution :

I don’t see the need for the Subject here. You could use the RxJS operators filter and map to accomplish your requirement and return the observable directly from the create() function.

I’ve also replaced the Array#find with Array#some function.

import { filter, map } from 'rxjs/operators';

public create(model: Model): Observable<number> {
  return this.GetAll().pipe(
    filter((result: any) => result.some(x => x.name != model.name)),
    map((result: any) => {
      model.id = result[result.length - 1].id + 1;
      EntitiesService.mock.push(model);
      return model.id;
    })
  );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading