I am currently working with Angular 4 and utilizing observables.
I have a requirement to share data between components as I am using BehaviorSubject along with observables.
Below is the code snippet:
import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Rx';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Http, Response } from '@angular/http';
public _searchResultOne = new Subject<any>();
searchResultOne$ = this._searchResultOne.asObservable();
constructor(private http: Http) {}
newsearch() {
return Observable.forkJoin(
this.http.get(API),
this.http.get(API)
)
.subscribe(latestValues => {
const [data_changes, data_all] = latestValues;
this._searchResultOne.next(latestValues);
})
}
getNewSearchResults(): Observable < any > {
return this.searchResultOne$;
}
I am displaying data using load more functionality. Result is fetched using getNewSearchResults()
function.
Here is my component code:
import { SearchService } from '../../shared/services/search.service';
import { ISubscription } from 'rxjs/Subscription';
results;
constructor(
public searchService: SearchService) {
}
ngOnInit() {
this.searchOne();
}
searchOne() {
this.subscription = this.searchService
.getNewSearchResults()
.subscribe(res => {
console.log("result", res);
var freelisting = res[1].response.docs;
this.results = this.results.concat(this.freelisitingArray);
}
}
I noticed that the response is being logged multiple times. What could be causing this issue?
The result is subscribed multiple times resulting in duplicate results. Is there a way to prevent multiple subscriptions?
I attempted to use this.subscription.unsubscribe()
in ngOnDestroy but still facing duplicate results. Any suggestions on how to resolve these issues?
Your advice would be greatly appreciated.
Thank you.