简体   繁体   中英

angular rxjs change async observable from websocket

Hi I am using angular 7 with rxjs async

in my component I am using ngFor with an async observer

<item-comp [item]="item" *ngFor="let item of groupsService.selectedItems$ | async; ">

</item-comp>

In my service I have an BehaviorSubject that gets emited when a group is selected by the user

  public groupSelected$: BehaviorSubject<any> = new BehaviorSubject(null);

and this is the selectedItems$ Observable :

public selectedItems$ = this.groupSelected$.pipe(
    switchMap((group: any) => {
        if (!group)
          return new EmptyObservable();

        return this.http.get('/api/'+ group)
          .pipe(
            map((res: any) => {
                return res.items;
              }
            )
          )
      }
    )
  )

this works , but now I need to be able to change specific items in response to websocket messages. I have a websocket connection that handles messages where items get updated. is there a way to do this using a reactive approach with rxjs ?

You can create an higher order functions for websocket updates then chain it up with your http request

const onUpdate=(items)=>updateFromWebSocket.pipe(
   map(itemUpdates=>{........ return updatedItems}
   startWith(items)
)

selectedItems$.pipe(switchMap(items=>onUpdate(items)).subscribe()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM