繁体   English   中英

在 angular 中将值从组件传递到服务

[英]Passing value from component to service in angular

我正在构建一个电子商务网站,当用户单击任何我想将产品网格更改为用户单击的复选框时。 我试图将 index 的值从 category-filter.component.ts 传递给 productgrid.service.ts 但每次我得到未定义的结果。

类别过滤器组件:

export class CategoryFilterComponent implements OnInit {

  selectedIndex: any = -1; // -1 because at screen load I do not want any checkboxes to be selected
  categoriesList: any= [];
  constructor(private categoryfilter: CategoryfilterService, private productList: ProductgridService) {
            this.categoryfilter.getCategories();
            this.categoriesList = this.categoryfilter.categoriesNames;
   }
  ngOnInit(): void {
  }

  changeSelection(event, index) {
    this.selectedIndex = event.target.checked ? index : undefined; // to only select one checkbox at a time
    index = this.selectedIndex ;
    this.productList.index = this.selectedIndex;
    console.log(this.productList.index) // works as intended
    // this.productList.saveIndex(this.selectedIndex);

  }
}

类别过滤器HTML:

<div class="filter-item" *ngFor="let category of categoriesList[0]; let index = index">
    <input type="checkbox" [ngModel]="selectedIndex === index" (change)="changeSelection($event, index)">
    <label>{{ category | titlecase }}</label>
</div>

产品网格服务:

export class ProductgridService {

  allProducts: any[] = [];
  index: any;
  constructor(private http: HttpClient) {
   }
   ngOnInit(): void {

  }
 

  getAllProducts() {
     console.log(this.index)
    if(this.index == 0) {
      console.log(this.index)
      this.http.get('https://dummyjson.com/products/category/smartphones').subscribe({
        next: (data) => {
          this.allProducts.push(data);
          console.log(this.allProducts);
        }
      })
    } else if (this.index == 1){
      console.log(this.index)
      this.http.get('https://dummyjson.com/products/category/laptops').subscribe({
        next: (data) => {
          this.allProducts.push(data);
          console.log(this.allProducts)
        }
      })
    }
    else {
      console.log(this.index) // this only works
      this.http.get('https://dummyjson.com/products').subscribe({
        next: (data) => {
          this.allProducts.push(data);
        }
      })
    }
  }
}

产品网格组件:

@Component({
  selector: 'app-products-grid',
  templateUrl: './products-grid.component.html',
  styleUrls: ['./products-grid.component.scss']
})
export class ProductsGridComponent implements OnInit {
  allProductList: any;
  singleCategorylist: any;
  index : number; 
  constructor(private productList: ProductgridService) {
    
    this.productList.getAllProducts();
    this.allProductList = this.productList.allProducts;
    // console.log(this.allProductList);
    // this.index = this.productList.index
    // console.log(this.index)
  }

  ngOnInit(): void {
    
  }

}

产品网格HTML:

<div class="col" *ngFor="let product of allProductList[0]?.products; let i = index">
  <img class="img-product" src="{{ product.thumbnail }}" alt="">
  <div class="dc">
    <p> -{{ product.discountPercentage }}% </p>
  </div>
  <p id="product-title">{{ product.title }}</p>
  <p id="product-description">{{ product.description }}.</p>
  <div class="product-price">
    <p> <span id="price-dc"><span style="font-weight:bold;">{{ product.price }} </span> <span>USD</span> </span> <span
        style="font-weight:bold;">477.85 </span><span>USD</span></p>
  </div>
  <p class="product-details">Brand: <span style="font-weight:bold;">{{ product.brand }}</span></p>
  <p class="product-details">Category: <span style="font-weight:bold;">{{ product.category }}</span></p>
  <p class="product-details">In stock: <span style="font-weight:bold;">{{ product.stock }}</span></p>
  <span class="product-rating"><img class="img-star" [attr.src]="'assets/images/star-17.png'" alt=""> <span
      style="color:#F4B000;"> {{ product.rating }} </span> <span>({{ product.id }})</span> </span>
  <button class="btn">ADD TO CART</button>
</div>

如果我的代码看起来杂乱无章,我很抱歉,因为我还是初学者,没有经验。

你检查过你真的得到了这里的期望值吗?

    index = this.selectedIndex ;
    //is index defined at this point?
    this.productList.index = this.selectedIndex;

也许 changeSelection 在您没有意识到的情况下被触发,请尝试这样编写:

    index = this.selectedIndex ;
    debugger
    this.productList.index = this.selectedIndex;

当此行被点击时,浏览器应该暂停,您可以检查该值。

此外,我认为公开服务变量并直接设置它不是一个好习惯。

顺便说一句,您可以为变量提供多个可能的值:

    private index: number | undefinded; 

这迫使您对所有可能的值进行检查。

在 Angular 中,您不必将注入的服务分配给组件 class。 因此,在 CategoryFilterComponent 的构造函数中删除所有分配。 在您的代码中,您可以直接使用该服务。 这样做之后,它应该可以工作。

另外请从您的服务中删除 ngOnInit 方法。 它仅适用于组件。

我希望这有帮助。

问题未解决?试试以下方法:

在 angular 中将值从组件传递到服务

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2023 STACKOOM.COM