Angular 2 Observable进入无限循环

时间:2017-05-17 04:22:47

标签: rxjs angular2-services

我对Angular2很新!我们有一个搜索方法,它创建一个async可观察并执行它。提供有效输入时,效果很好。但无效输入导致无限循环。如果您发现问题,请告诉我。

请参阅下面的代码。

const ngPromiseToObservable = <T>(p: ng.IHttpPromise<ng.IHttpPromiseCallbackArg<T>>): Observable<ng.IHttpPromiseCallbackArg<T>> => {
    const o = new Subject();

    p.catch((e) => o.error(e));
    p.then((v) => o.next(v));

    return o;
};

export class HttpObservable
{
    public static $inject = [
        "$rootScope",
        "$http",
        "HttpErrors",
    ];

    constructor(
        private $rootScope: ng.IScope,
        private $http: ng.IHttpService,
        private httpErrors: Subject<Object>
    ) {}

    handleHttpResponseErrors<T>(o: Observable<T>): Observable<T>
    {
        return o.do(
            _.noop,
            (e: HttpResponseError) => this.httpErrors.next(e),
            _.noop
        );
    }

    applyAsyncOnAction<T>(o: Observable<T>): Observable<T> 
    {
        let applyAsync: () => void = () => {

            return this.$rootScope.$applyAsync();
        };

        return o.do(applyAsync, applyAsync, applyAsync);
    }

    // tslint:disable-next-line:no-any
    post<T>(url: string, data: any, config?: Object): Observable<T>
    {
        return this.handleHttpResponseErrors(this.applyAsyncOnAction(ngPromiseToObservable(this.$http.post(url, data, config)).map((x) => x.data)));
    }

    // tslint:disable-next-line:no-any
    put<T>(url: string, data: any, config?: Object): Observable<T> 
    {
        return this.handleHttpResponseErrors(this.applyAsyncOnAction(ngPromiseToObservable(this.$http.put(url, data, config)).map((x) => x.data)));
    }

    get<T>(path: string): Observable<T> 
    {
        return this.handleHttpResponseErrors(this.applyAsyncOnAction(ngPromiseToObservable(this.$http.get(path)).map((x) => x.data)));
    }

0 个答案:

没有答案