[英]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 方法。 它僅適用於組件。
我希望這有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.