0

我正在用一些产品建立一个电子商店。用户可以添加到购物车,他可以看到他添加的产品。我分为三类。一个类别是我显示所有产品的所有产品和一个我显示特定产品的水果和面包类别..一切正常但是当我更改类别而不单击添加到购物车按钮时,角度执行 addToCart 方法..我认为它是多个订阅和内存泄漏的问题..我怎样才能用更好的编码来做到这一点?这是我的 ts 和 html 角度文件。

我的产品.ts

import {Component, OnDestroy, OnInit} from '@angular/core';
import {CategoryService} from '../category.service';
import {ActivatedRoute} from '@angular/router';
import {Subject} from 'rxjs/index';
import 'rxjs/add/operator/takeUntil';
import {ShoppingCartService} from '../services/shopping-cart.service';
import {Product} from '../models/product';




@Component({
  selector: 'app-products',
  templateUrl: './products.component.html',
  styleUrls: ['./products.component.css'],

})
export class ProductsComponent implements OnInit, OnDestroy {

  products: any;
  filteredproducts: any;
  category: any;
  res: any;
  categoryid: any;
  cartId: any;
  private ngUnsubscribe: Subject<any> = new Subject();





  constructor(private service: CategoryService,
              private route: ActivatedRoute,
              private cartService: ShoppingCartService) {


  }


ngOnInit() {

  this.route.queryParamMap.takeUntil(this.ngUnsubscribe).subscribe(params => {
    this.category = params.get('category');
    this.cartId = localStorage.getItem('cartId');
    if (this.category) {
        setTimeout(() => {
            this.service.allProductNames(this.category, this.cartId).takeUntil(this.ngUnsubscribe).subscribe(data => {
                this.filteredproducts = this.products = data;
            });
        }, 500);

    } else {
        if (this.cartId === null) {this.cartId = -1; }
        setTimeout(() => {
            this.service.getProducts(this.cartId).takeUntil(this.ngUnsubscribe).subscribe(data => {
                this.filteredproducts = data;
            });
        }, 500);


    }

  });


}


    addToCart(products: Product) {

        const cartId = this.cartService.getOrCreateCartId();

        if (!cartId) {
         const imero = new Date().getTime();
         this.cartService.create(imero).takeUntil(this.ngUnsubscribe).subscribe(res => {
           this.res = res;
           localStorage.setItem('cartId', this.res.id);
           this.route.queryParamMap.takeUntil(this.ngUnsubscribe).subscribe(params => {
           this.categoryid = params.get('category');
           if (this.categoryid) {
            this.cartService.createItem(products.id, this.res.id).
            takeUntil(this.ngUnsubscribe).subscribe(res1 => {
                setTimeout(() => {
                    this.service.allProductNames(this.category, this.res.id).takeUntil(this.ngUnsubscribe).subscribe(data => {
                        this.filteredproducts = this.products = data;});
                }, 500);

            });

           } else {
           this.cartService.createItem(products.id, this.res.id).takeUntil(this.ngUnsubscribe).subscribe(res2 => {
               setTimeout(() => {
                   this.service.getProducts(this.res.id).takeUntil(this.ngUnsubscribe).subscribe(data => {
                       this.filteredproducts = data;
                   });
               }, 500);

           } );
              }

                });
            });

        }


        else {
            this.route.queryParamMap.takeUntil(this.ngUnsubscribe).subscribe(params => {
                this.categoryid = params.get('category');
                this.cartId = localStorage.getItem('cartId');
                if (this.category) {
                    this.cartService.createItem(products.id, this.cartId).takeUntil(this.ngUnsubscribe).subscribe(res1 => {});
                    setTimeout(() => {
                        this.service.allProductNames(this.category, this.cartId).takeUntil(this.ngUnsubscribe).subscribe(data => {
                            this.filteredproducts = data;
                            });

                    }, 500);

                } else {
                    this.cartService.createItem(products.id, this.cartId).takeUntil(this.ngUnsubscribe).subscribe(res1 => {});
                    setTimeout(() => {
                        this.service.getProducts(this.cartId).takeUntil(this.ngUnsubscribe).subscribe(data => {
                            this.filteredproducts = data;
                            console.log(this.products);});

                    }, 500);
                }





            });

        }
    }



ngOnDestroy() {
  this.ngUnsubscribe.next();
  this.ngUnsubscribe.complete();
}

}

我的产品.html

<div class="row">
  <div class="col-sm-3">
<app-product-filter></app-product-filter>
  </div>
  <div class="col-sm-9">
    <div class="row">
      <ng-container  *ngFor="let p of filteredproducts; let i = index">
        <div class="col">
            <div class="card">
                <img  class="card-img-top" src="{{p?.imageUrl}}" style="max-height: 200px; width: 100%;">
                <div class="card-body">
                    <h5 class="card-title">{{p?.title}}</h5>
                    <p class="card-text">{{p?.price | currency: 'EUR': symbol }}</p>
                </div>
                <div class="card-footer">
                    <button (click)="addToCart(p)" class="btn btn-primary btn-block">Add to Cart</button>
                    <div *ngIf="p?.quantity!=0">{{p?.quantity}}</div>
                </div>
            </div>

        </div>
        <div *ngIf="(i+1) % 2 === 0" class="w-100"></div>
      </ng-container>

    </div>
  </div>
</div>
4

1 回答 1

0

你永远不应该订阅订阅。您可以像这样更改代码:

this.route.queryParamMap.mergeMap(params => {
    this.category = params.get('category');
    this.cartId = localStorage.getItem('cartId');
    if (this.category) {
       return this.service.allProductNames(this.category, this.cartId);
    } else {
        if (this.cartId === null) {
           this.cartId = -1;
        }
        return this.service.getProducts(this.cartId);    
    }
  }).takeUntil(this.ngUnsubscribe).subscribe(data => this.filteredproducts = data);

您应该只订阅一次您的 queryParams,它应该在 ngOnInit 中。这些是您应该在添加到购物车方法中考虑的以下几点:

  1. 您已经在您的方法中声明了类别属性使用它。不要订阅 queryParams。
  2. 使用 mergeMap rxjs 运算符删除嵌套订阅。
  3. 组件销毁时,嵌套订阅不会取消订阅。
  4. 您不应该在订阅中使用 setTimeout。使用 debounceTime rxjs 运算符
于 2018-10-04T11:24:22.947 回答