How to synchronise Angular2 http get?

后端 未结 8 1319
無奈伤痛
無奈伤痛 2021-01-07 19:27

I understand using observable I can execute a method when the request is completed, but how can i wait till a http get is completed and return the response using in ng2 http

相关标签:
8条回答
  • 2021-01-07 19:53

    How about to use $.ajax(of jQuery) or XMLHttpRequest.

    It can use as asynchornize.

    0 讨论(0)
  • 2021-01-07 19:58

    Another solution would be to implement a priority queue of sort.

    From what I understand http requests do not get executed until you add subscribers. Therefore, you can do something like this:

    Observable<Response> observable = http.get("/api/path", new RequestOptions({}));
    
    requestPriorityQueue.add(HttpPriorityQueue.PRIORITY_HIGHEST, observable,
                     successResponse => { /* Handle code */ }, 
                     errorResponse => { /* Handle error */ });
    

    This assumes that requestPriorityQueue is a service injected into your component. The priority queue would store entries in an array in the following format:

    Array<{
        observable: Observable<Response>, 
        successCallback: Function, 
        errorCallback: Function
    }>
    

    You would have to decide how the elements are added to your array. Finally, the following will happen in the background:

    // HttpPriorityQueue#processQueue() called at a set interval to automatically process queue entries
    

    The processQueue method would do something like this:

    protected processQueue() {
        if (this.queueIsBusy()) {
            return;
        }
    
        let entry: {} = getNextEntry();
        let observable: Observable<Response> = entry.observable;
    
        this.setQueueToBusy(); // Sets queue to busy and triggers an internal request timeout counter.
        observable.subscribe()
            .map(response => {
                this.setQueueToReady();
                entry.successCallback(response);
            })
            .catch(error => {
                this.setQueueToReady();
                entry.errorCallback(error);
            });
    }
    

    If you are able to add new dependencies you could try using the following NPM package: async-priority-queue

    0 讨论(0)
提交回复
热议问题