我創建了一項服務,它使用RxJS
來包裝$http
調用。Angular 1服務 - RxJS共享運營商不能正常工作
我有幾個組件訂閱相同的observable,我希望他們共享AJAX結果,而不是多個請求。
服務代碼:
export function SearchService($http) {
'ngInject';
const autocompleteResults$ = new Subject()
.debounceTime(250)
.switchMap(query => Observable.fromPromise($http.post('/search', { query })))
.share()
.map(result => result.data);
function autocomplete(query) {
autocompleteResults$.next(query);
}
return {
autocomplete,
autocompleteResults$
};
}
組件的代碼:
export const myComponent = {
bindings: {
query: '<'
},
templateUrl: templateUrl,
controller: myController
};
function myController($SearchService) {
'ngInject';
const $ctrl = this;
$ctrl.$onInit = $onInit;
$ctrl.$onChanges = $onChanges;
function $onInit() {
SearchService.autocompleteResults$
.subscribe(
handleSuccess,
handleError
);
}
function $onChanges(changes) {
if (changes.query && changes.query.currentValue)
SearchService.autocomplete(changes.query.currentValue);
}
}
我有,要查詢的變化做出反應的myComponent
活性組分。
由於Angular
服務是單身,每個組件應該得到訂閱它的時候,卻總是有相同的觀察到的實例2 AJAX調用,而不是1
我使用share
,publish
,publishReplay
,shareReplay
嘗試和refCount
運營商沒有成功。