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

Angular 如何添加监听角度变化的函数?,angular,typescript,frontend,listener,product,Angular,Typescript,Frontend,Listener,Product,我有一个产品列表,点击一个产品后,打开产品详细信息,其中有该产品的详细信息。URL路径是产品的id,即获取并在数据库中搜索该产品。但要查看此产品的数据,我必须单击按钮。如何自动执行,然后监听更改 product-details.component.ts: export class ProductDetalisComponent implements OnInit { private ngUnsubscribe = new Subject(); product = []; produ

我有一个产品列表,点击一个产品后,打开产品详细信息,其中有该产品的详细信息。URL路径是产品的id,即获取并在数据库中搜索该产品。但要查看此产品的数据,我必须单击按钮。如何自动执行,然后监听更改

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>
产品
名称:{{product.Name}

价格:{{product.Price}}

Id:{{product.\u Id}


你的意思是这样的吗

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)
    );
  }
}
导出类ProductDetalisComponent实现OnInit{
构造函数(私有productService:productService,私有路由:ActivatedRoute){}
产品=[];
产品标识;
恩戈尼尼特(){
this.route.paramMap.subscribe(params=>{
this.product_id=params.get('productId');
this.getProductById();//{
控制台日志(res);
本产品=res;
},
err=>console.log(err)
);
}
}

是的,这正是我的意思:D哇,我想我应该使用observable或类似的东西,但它很简单,而且很有效。非常感谢你的帮助:)你已经在使用observable,我发现你没有退订,这会导致内存泄漏。我建议你看这篇文章:谢谢:)根据你的建议,我刚刚添加了“取消订阅”功能,但我不确定它是否工作正常,请检查我是否正确。我会将其作为下一个答案发布。不要将其作为答案发布。只需编辑您的问题。好的,我完整地阅读了您的文章。不幸的是,我只是初学者,而且比我领先了很多。但非常感谢:)我没有注意到我的问题把这个方法放在错误的地方。