微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何添加侦听Angular中的更改的函数?

如何解决如何添加侦听Angular中的更改的函数?

我有一个产品列表,单击某个产品后,将打开产品详细信息,其中包含该产品的详细信息。 URL路径是产品的ID,即在数据库获取然后搜索该产品的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>

解决方法

您的意思是这样的吗?:

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。