Search code examples
angularobservablesubscription

Multiplied subscription


In one component I have two subscriptions, one for query parameters, one for http GET request. On this page user also has an option to switch between different types of data (only one type can be displayed). When user clicks one option, query parameter is updated and the subscription is updated, so the http GET request is called again and the data is also updated, as below:

constructor(private service: DataService, private route: ActivatedRoute) {}

ngOnInit() {
        this.route.queryParams.subscribe(params => {
            this.dataType = params["dataType"];
                this.service
                    .getData(this.dataType)
                    .subscribe(data => {
                        this.data=data;
                    })
        })
}

In html:

  [queryParams]="{ dataType: row.dataType}"

The problem is, that every time user clicks different type of data, new subscription is created from the http GET request, because everything is happening within the same component. So, when component is created: 2 subscriptions, user clicks new data type: new data loaded and 3 subscriptions, user click different data type, new data loaded and 4 subscriptions and so on. As you can imagine after 4-5 clicks the page just crashes.

I've been trying to find a solution for this problem (specifically loading data in the same component based on users choice), but I cant figure out how to do that. Any help would be appreciated


Solution

  • This code will not solve your issue, but you're using two asynchronous event one in the other. This is not a good practise.

    You can update your code with that :

    this.route.queryParams.pipe(
        switchMap(params => this.service.getData(params["dataType"]))
    ).subscribe(data => this.data = data);
    

    To solve your subscription issue, did you try to add a ngOnDestroy() function ?