Ravi Sahu
Ravi Sahu

Reputation: 43

Angular 2 http get() funtion is not sending request to backend API after first call

I need to call the search API each time when a filter is added/removed to it. First time when the component is being loaded then its working fine and sending the request to backed controller. But next time when I apply any filter on it and again sending the request to same API then http.get() function is being called but its not sending request to backed controller. I checked in network tab but no request is there. Below is the code which is executing correctly to send the API call.

constructor(private http: Http, private filterService: FilterService, private dataService: DataService) {

    this.subscription = this.filterService.getFilterListObservable()
        .subscribe((data) => {
            let filterKeysObj = this.createFilterKeyObject(data.activeFilters);
            return this.search(filterKeysObj);
        });
}

private createFilterKeyObject(activeFilters) {
    let filterKeysObj = {};

    activeFilters.forEach((element) => {
        if (!filterKeysObj[element.type]) {
            filterKeysObj[element.type] = [];
        }
        filterKeysObj[element.type].push(element.item.id || element.item.label);
    });

    return filterKeysObj;
}

public search(filterKeysObj: Object) {

    let params: URLSearchParams = new URLSearchParams();
    if (filterKeysObj) {
        for (let key in filterKeysObj) {
            params.set(key, encodeURIComponent(filterKeysObj[key].join()));
        }
    }

    /* 
    // This code is to fetch the static data from a data service.
    let questionList = this.dataService.questions;
    return Observable.of(questionList);
    */

    // Http request-
    return this.http.get(`/api/tasks/search`, { search: params })
        .map((res: Response) => {
            return res.json();
        });
}

}

Upvotes: 0

Views: 334

Answers (1)

Kirk Larkin
Kirk Larkin

Reputation: 93153

You need to subscribe to the Observable being returned from search. You are working with a cold observable and therefore need to subscribe in order to start the sequence. See here for more information about hot and cold observables.

Upvotes: 1

Related Questions