Programing

관찰 가능>에서 특정 요소를 제거하는 방법

c10106 2022. 3. 19. 10:46
반응형

관찰 가능>에서 특정 요소를 제거하는 방법

장소의 배열은 관찰할 수 있다.

places: Observable<Array<any>>;

템플릿에서 비동기 파이프와 함께 사용:

<tr *ngFor="let place of places | async">
  ...
</tr>

사용자 작업 후 이 배열에서 특정 ID의 플레이스를 제거해야 한다.내 코드에 이런 게 있는데 안 먹히네

deletePlace(placeId: number): void {
  this.apiService.deletePlace(placeId)
  .subscribe(
    (res: any) => {
      this.places
        .flatMap((places) => places)
        .filter((place) => place.id != placeId);
    }, 
    (err: any) => console.log(err)
  );    
}  

당신은 이것과 함께 나를 도와줄수 있나요?

관찰할 수 있는(즉, 상태를 유지하지 않음)을 "업데이트"할 수는 없지만 이를 통해 이벤트에 반응할 수 있기 때문에 이런 식으로 할 수는 없다.

사용 사례에 대해, 나는 다음 항목을 활용하겠다.scan연산자와 두 스트림을 하나의 스트림으로 병합:

  • 최초 적재용 1개
  • 삭제 이벤트에 대한 다른 이벤트

여기 샘플이 있다.

let obs = this.http.get('/data').map(res => res.json());

this.deleteSubject = new Subject();

this.mergedObs = obs.merge(this.deleteSubject)
.startWith([])
.scan((acc, val) => {
  if (val.op && val.op==='delete') {
    var index = acc.findIndex((elt) => elt.id === val.id);
    acc.splice(index, 1);
    return acc;
  } else {
    return acc.concat(val);
  }
});

요소 삭제를 트리거하려면 제목에 대한 이벤트를 보내십시오.

this.deleteSubject.next({op:'delete', id: '1'});

다음 plunkr:

필터 연산자를 활용할 수 있는 방법:

this.places$
        .pipe(
            map(places => {
                // Here goes some condition, apply it to your use case, the condition only will return when condition matches
                return places.filter(place => place.placeId !== 0);
            }),
            map(response => (this.users$ = of(response)))
        )
        .subscribe(result => console.warn('Result: ', result));

필터 기능은 불변성이므로 원래 배열을 변경하지 않는다.

deletePlace 기능을 다음과 같은 것으로 변경한다.-

deletePlace(placeId: number):  void {
  this.apiService.deletePlace(placeId)
  .subscribe(
    (res: any) => {
      this.places = this.places.filter((place) => place.id != placeId);
    }, 
    (err: any) => console.log(err)
  );    
}  

RxJS 버전 6

RxJS 6과 함께 승인된 답변 사용typescript에러를 던질 것이다 왜냐하면observables종류가 다르다사용하는 것이 좋다combineLatest, 당신은 또한 사용할 수 있다.zip하지만 소용없을거야! 방금 이유를 물어봤니? 답은 여기 있어 :)

combineLatest([
  this.items$,
  this.deleteItem$
]).pipe(
  takeUntil(this.onDestroy),
  tap(([items, deleteItem]) => {
    if (deleteItem && deleteItem.op === 'deleteItem') {
      var index = items.findIndex((item) => item.id === deleteItem.id);
      if (index >= 0) {
        items.splice(index, 1);
      }
      return items;
    }
    else {
      return items.concat(deleteItem);
    }
  })
).subscribe();

그럼 이벤트를 보내주면 되겠네..

this.deleteItem$.next({ op: 'deleteItem', id: '5e88fce485905976daa27b8b' });

누군가에게 도움이 되었으면 좋겠다..

참조URL: https://stackoverflow.com/questions/38181954/how-to-remove-specific-element-from-observablearrayany

반응형