IT이야기

switchMap: 여러 개의 요청이 트리거됨

cyworld 2022. 3. 16. 22:07
반응형

switchMap: 여러 개의 요청이 트리거됨

나는 각도 2 RC-4를 사용하고 있다.입력란에 변경 사항이 있을 때마다 네트워크 요청을 하려고 한다.하지만 그 요청은 두 번이나 걸려오고 있다.

내 코드는 다음과 같다.

구성 요소.ts

this.term = new Control();

this.suggestions = this.term.valueChanges
      // .debounceTime(1000)
      // check if the search term's length is >= 1
      .filter(term => term && term.length)

      // switchMap only subscribes to one observable at a time so if a new key is
      // pressed before the response of previous request has been recieved, it
      // automatically un-subscribes from the previous observable thus cancelling the previous
      // request.
      .switchMap(term => this._suggestionsService.getSuggestions(term, uuid))

컴포넌트.component.properties

<ul [hidden]='!(suggestions | async)?.length'>
<li *ngFor='let suggestion of suggestions | async'>{{suggestion.name}}</li>
</ul>

제안.서비스.ts

getSuggestions(term){
 return this.http.get('some-url')
      .map((res: Response) => res.json());
}

이것은 네트워크 요청을 2번 만든다.그러나 비동기식 파이프를 사용하는 대신 컴포넌트의 코드를 약간만 변경하고 수동으로 가입하면 네트워크 요청이 한 번만 이루어진다.

구성 요소.ts

this.term.valueChanges
  .filter(term => term && term.length)
  .switchMap(term => this._suggestionsService.getSuggestions(term, uuid))
  .subscribe(value => this.suggestions = value);

컴포넌트.component.properties

<ul [hidden]='!suggestions.length'>
<li *ngFor='let suggestion of suggestions'>{{suggestion.name}}</li>
</ul>

결과는 둘 다 좋다.네트워크 요청 수만이 나의 관심사다.내가 놓치고 있는 관찰용품에 대한 개념이 있는 것 같아.

문제는 2개가 있다는 것이다.async관찰 가능이 여러 번 구독되어 요청이 두 번 이루어지는 템플릿.

사용.share요령을 터득할 것이다:

this.suggestions = this.term.valueChanges
    .filter(term => term && term.length)
    .switchMap(term => this._suggestionsService.getSuggestions(term, uuid))
    .share();

참조URL: https://stackoverflow.com/questions/38754499/switchmap-multiple-2-requests-getting-triggered

반응형