Melvin Otieno
Melvin Otieno

Reputation: 79

How to get parameters from URL in Angular

I'm including routing in my Angular 7 application on a feature module. A component belonging to this feature needs to get the route parameter. How do I do this?

I've tried using the method shown in the docs as shown in the code below. I have commented which one works and which one doesn't. I want to use the second method which doesn't work since it maps the results to the products$ observable that I will use in my template. What could be the problem?

import { Component, OnInit } from "@angular/core";
import { ActivatedRoute, ParamMap } from "@angular/router";
import { Observable } from "rxjs";
import { switchMap } from "rxjs/operators";

import { Product } from "@shared/interfaces/product.interface";

import { ProductsService } from "../products.service";

@Component({
  templateUrl: "./product-list.component.html",
  styleUrls: ["./product-list.component.css"]
})
export class ProductListComponent implements OnInit {
  products$: Observable<Product[]>;

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

  ngOnInit() {
    this.route.paramMap.subscribe((params: ParamMap) => {
      console.log(params.get("category")); // this works
    });

    this.products$ = this.route.paramMap.pipe(
      switchMap(params => {
        console.log(params.get("category")); // this doesn't work
        return this.service.getProducts(params.get("category"));
      })
    );
  }
}

I expected the second method to log the results but it doesn't at all.

Upvotes: 0

Views: 674

Answers (3)

Thivanka Saranatha
Thivanka Saranatha

Reputation: 362

Andrei is true rxjs observables are lazy problem will solve by adding this.products$.subscribe() but unlike angular Router the other service subscription will not stop until you unsubscribe it. So remember to unsubscribe in on ngOnDestroy()

Upvotes: 1

Melvin Otieno
Melvin Otieno

Reputation: 79

I have accepted Andrei's answer but i have also learned that adding | async in the template file solves the problem because as Andrei noted, no subscription had taken place yet

Upvotes: 1

Andrei
Andrei

Reputation: 12001

rxjs observables are lazy, so if no subscription is done, your source is not even trying to get data. Add this.products$.subscribe() in the end of ngOnInit and you will see your console.log result.

Upvotes: 1

Related Questions