首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >多订阅角6

多订阅角6
EN

Stack Overflow用户
提问于 2018-10-04 09:47:44
回答 1查看 2.2K关注 0票数 0

我正在用一些产品建造一家电子商店.用户可以添加到购物车,他可以看到他添加的产品。我有三种类型。一个类别是显示所有产品的所有产品,一个水果和面包类别显示特定的products..Everything很好,但是当我不单击add to cart按钮角就更改类别时,执行addToCart方法。我认为多个订阅和内存leak..How存在问题,可以用更好的编码来完成吗?这里是我的ts和html角文件。

我的products.ts

代码语言:javascript
复制
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();
}

}

我的products.html

代码语言:javascript
复制
<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>
EN

回答 1

Stack Overflow用户

发布于 2018-10-04 11:24:22

你不应该订阅。您可以这样修改代码:

代码语言:javascript
复制
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中。在add to cart方法中应该考虑以下几点:

  1. 您已经声明了类别属性,请在方法中使用它。不要订阅queryParams。
  2. 使用mergeMap rxjs操作符删除嵌套订阅。
  3. 当组件破坏时,嵌套订阅不会取消订阅。
  4. 您不应该在订阅中使用setTimeout。使用debounceTime rxjs操作符
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52643710

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档