多个订阅角度6

时间:2018-10-04 09:47:44

标签: angular rxjs observable angular6 rxjs6

我正在建立一些商品的电子商店。用户可以将其添加到购物车,并且可以看到他添加的产品。我分为三类。一类是我显示所有产品的所有产品,而一类水果和面包则显示特定产品的面包。一切正常,但是当我更改类别而未单击“添加到购物车”按钮中的角度时,执行addToCart方法。多个订阅和内存泄漏的问题。如何通过更好的编码实现?这是我的ts和html角文件。

我的产品。

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>

1 个答案:

答案 0 :(得分: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. 您已经声明了category属性,请在您的方法中使用它。不要订阅queryParams。
  2. 使用mergeMap rxjs运算符删除嵌套的订阅。
  3. 嵌套销毁不会在组件销毁时取消预订。
  4. 您不应在订阅中使用setTimeout。使用debounceTime rxjs运算符
相关问题