我创建了一项服务,它使用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
运营商没有成功。