【问题标题】:How to add function that listen for changes in Angular?如何添加监听Angular变化的功能?
【发布时间】:2020-10-20 09:32:38
【问题描述】:

我有一个产品列表,点击一个产品后,打开产品详细信息,其中有该产品的详细信息。 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>

【问题讨论】:

    标签: angular typescript frontend listener product


    【解决方案1】:

    你的意思是这样的吗?:

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

    【讨论】:

    • 是的,这正是我的意思 :D 哇,我认为我应该使用 observable 或类似的东西,但它是如此简单并且有效。非常感谢您的帮助:)
    • 您已经在使用 observable 并且我看到您没有取消订阅,这可能会导致内存泄漏。建议你看看这篇文章:netbasal.com/when-to-unsubscribe-in-angular-d61c6b21bad3
    • 谢谢 :) 根据您的建议,我刚刚添加了取消订阅功能,但我不确定它是否运作良好,请您检查一下我是否做得正确?我会把它作为下一个答案发布
    • 请勿将其作为答案发布。只需编辑您的问题。
    • 好的,我完全阅读了你的文章。不幸的是,我只是初学者,而且还远远领先于我。但是非常感谢:)我没有注意到我把这个方法放在了错误的地方。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-04
    • 2020-11-11
    • 2019-06-28
    • 2016-07-15
    • 1970-01-01
    • 2021-09-21
    • 1970-01-01
    相关资源
    最近更新 更多