Home > Enterprise >  subscribe observable (as subject)
subscribe observable (as subject)

Time:05-17

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:

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?

CodePudding user response:

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;
    })
  );
}
  • Related