반응형
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
반응형
'IT이야기' 카테고리의 다른 글
사전 객체의 Vue + Vuex 반응도 (0) | 2022.03.16 |
---|---|
두 관측치의 첫 번째 값이 모두 방출된 후 Zip이 값을 방출하지 않음 (0) | 2022.03.16 |
각도 2 입력 유효성 검사를 수동으로 트리거하는 방법 (0) | 2022.03.16 |
Python 3에서 Raw_input을 사용하는 방법 (0) | 2022.03.16 |
각도 2 템플릿 방법 대 게터 (0) | 2022.03.16 |