如何添加监听 Angular 变化的函数?

How to add function that listen for changes in Angular?

我有一个产品列表,点击一个产品后,会打开产品详细信息,其中有该产品的详细信息。 URL 路径是商品的id,也就是获取然后在数据库中搜索该商品。但是要查看该产品的数据,我必须单击按钮。如何自动完成然后监听变化?

产品-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();
  }

}

产品-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>

你的意思是这样的吗?:

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