0

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.

2
  • Does anything currently .subscribe() (or | async) to this.products$? Commented Mar 23, 2019 at 11:12
  • no i hadn't added any of those. now that i have an | async method in my template it works. thanks Commented Mar 23, 2019 at 11:20

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.