PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, May 9, 2022

[FIXED] How to add function that listen for changes in Angular?

 May 09, 2022     angular, frontend, listener, product, typescript     No comments   

Issue

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)
    );
  }
}


Answered By - StPaulis
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing