SeaBiscuit
SeaBiscuit

Reputation: 2611

Fetch ActivatedRoute param and queryParam in Angular 2

What is the best way to get entire url content in angular 2. Basically i need params and queryParams. Right now i am stuck here :

ngOnInit() {
this.activatedRoute.queryParams.subscribe(queryParam =>{
  console.log(queryParam);
});
this.activatedRoute.params.subscribe(params =>{
  const category = params['category'];
  this.seoService.setTitle(category);

  // This is wrong because i also need queryParams here
  this.categoryService.updateCategory(category);

     });
   }
}

This is the best that i could come up with. I aim for url`s like this /category-name?page=1&sortBy=something&size=30&sortOrder=ASC&L=UTF-8

I am trying to get the next value out of activatedRoute and assemble an object with all information and then call back-end service.

Upvotes: 1

Views: 545

Answers (2)

SeaBiscuit
SeaBiscuit

Reputation: 2611

I did accept previous answer, but it turned out it had a problem with queryParams. Sometimes queryParams were present sometimes not, and because of that i had inconsistent values.Using withLatestFrom instead of combineLatest did the trick.

this.activatedRoute.params.withLatestFrom(this.activatedRoute.queryParams)
                          .subscribe(([params,queryParam ]) =>{
            const category = params['category'];
            let urlSearchParams : URLSearchParams = this.assembleSearchParams(queryParam);
            ...
}

Upvotes: 0

Sergey Sokolov
Sergey Sokolov

Reputation: 2839

You can get both with combineLatest:

Rx.Observable.combineLatest(
    this.activatedRoute.queryParams,
    this.activatedRoute.params)
.subscribe(([queryParam, params]) => {
    ...
});

Upvotes: 1

Related Questions