Search code examples
angulartypescriptfrontendlistenerproduct

How to add function that listen for changes in Angular?


I have a list of products, after clicking on a product, product-details opens, in which there are details of this product. The URL path is the id of the product, that is getting and then searching for that product in the database. But to view the data for this product I have to click on the button. How to do it automatically and then listen for changes?

product-details.component.ts:

export class ProductDetalisComponent implements OnInit {
  private ngUnsubscribe = new Subject();

  product = [];
  product_id;

  constructor(private productService: ProductService, private route: ActivatedRoute) { }


  ngOnInit() {

    this.route.paramMap.pipe(takeUntil(this.ngUnsubscribe))
      .subscribe(params => 
      {
          this.product_id = [params.get('productId')];
          this.getProductById();
      });
  }

  getProductById() {
    this.productService.getProductById(this.product_id)
      .subscribe(
        res => {
          this.product = res;
        },
        err => console.log(err)
      );
  }

  ngOnDestroy() {
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();
  }

}

product-details.component.html:

  <button type="button" (click)="getProductById();">Product</button>

  <p>Name: <a> {{product.name}} </a></p>
  <p>Price: <a> {{product.price}} </a></p>
  <p>Id: <a> {{product._id}} </a></p>

Solution

  • Do you mean something like this?:

    export class ProductDetalisComponent implements OnInit {
    
      constructor(private productService: ProductService, private route: ActivatedRoute) { }
    
      product = [];
      product_id;
    
      ngOnInit() {
        this.route.paramMap.subscribe(params => {
          this.product_id = params.get('productId');
          this.getProductById(); // <=====
        });
      }
    
      getProductById() {
        this.productService.getProductById(this.product_id).subscribe(
          res => {
            console.log(res);
            this.product = res;
          },
          err => console.log(err)
        );
      }
    }