在组件之间传递数据,其中之一是 Angular 中的 routerOutlet

问题描述 投票:0回答:1

我在仪表板组件内有类别和产品组件。我想将数据从类别组件传递到产品组件,但 ProductComponents 内部有 routerOutlet 。我遇到了这个问题。

仪表板屏幕

dashboard.component.html

<div class="columns">
    <div class="column is-2">
        <app-category></app-category>
    </div>
    <div class="column is-10">
        <router-outlet ></router-outlet>
    </div>
</div>

category.component.html

<div class="container">
    <input type="checkbox" id="menu-toggle">
    <label for="menu-toggle" class="hamburger-menu" (click)="showCategoryList()"><span></span></label>
    <div class="content">
        <p class="menu-title title is-4" style="font-weight: normal">Categories</p>
        <ul class="menu-list">
            <li class="subtitle category-list" *ngFor="let category of categories">
                <input type="checkbox" [id]="category.id" (change)="filterProductsByCategory($event)">
                <label [htmlFor]="category.id">{{category.name}}</label>
            </li>
        </ul>
        <div class="filter mb-3"><button (click)="getFilterData()">Filter</button></div>
    </div>
</div>

类别.component.ts

export class CategoryComponent implements OnInit{

  categories: Category[] = [];
  activatedCategory?: Category;
  dataLoaded = false;
  currentCategories: Category[] = [];
  selectedCategory: Category[]  = [];

  constructor(private categoryService: CategoryService) { }

  hamburgerMenu: HTMLElement = document.querySelector(".hamburger-menu")!;
  ngOnInit(): void {
    this.getCategories();
   
  }

  getCategories() {
    this.categoryService.getCategories().subscribe(response => {
      this.categories = response.data;
      this.dataLoaded = true;
    })
  }
  
  getActivatedCategory(category: Category) {
    this.activatedCategory = category;
  }

  setCurrencyCategory(category: Category) {
    this.currentCategories.push(category);
  }

  showCategoryList() {
    var content = document.querySelector(".content")! as HTMLElement;
    if (content.style.display === "block") {
      content.style.transition = "0.5s ease";
      content.style.display = "none";
    }
    else {
      content.style.transition = "0.5s ease";
      content.style.display = "block";
    }
  }

  filterProductsByCategory(event: any){
    if(event.target.checked){
      console.log(event.target.id);
      this.selectedCategory.push(event.target.id);
    }else{
      const id = event.target.id;
      this.selectedCategory.forEach((category, index) => {
        if(category.id === id){
          const index = this.selectedCategory.indexOf(category);
          console.log(index);
          this.selectedCategory.splice(index, 1);
        }
      })
    }
  }

  getFilterData(){
    const pars = this.selectedCategory.map((category: any) => {
      return parseInt(category);
    })
    console.log(this.selectedCategory);
  }
}

products.component.html

<div id="products">   
    <div *ngIf="!dataLoaded" class="lds-ring"><div></div><div></div><div></div><div></div></div>
    <h1 class="title">Products</h1>
    <div id="search-box">
      <input class="input mb-4" type="text" placeholder="Filter by product name" [(ngModel)]="searchText">
      <button class="button is-dark" type="button">Search</button>
    </div>
    
    <table *ngIf="dataLoaded && products" class="table is-hoverable is-fullwidth  is-striped" >
      <thead>
        <tr>
            <th>ID</th>
            <th>Product Name</th>
            <th>Category ID</th>
            <th>Price</th>
            <th>Unit In Stock</th>
            <th>Unit On Order</th>
            <th>Reorder Level</th>
        </tr>
      </thead>
      <tbody>
        <tr *ngFor="let product of products | filterProducts: searchText">
          <td>{{ product.id }}</td>
          <td>{{ product.name }}</td>
          <td>{{ product.categoryID }}</td>
          <td>{{ product.unitPrice| currency: "TR" : '₺' : '2.2-2'  }}</td>
          <td>{{ product.unitsInStock }}</td>
          <td>{{ product.unitsOnOrder }}</td>
          <td>{{ product.reorderLevel }}</td>
        </tr>
    </table>
    <div *ngIf="!products">No Products!</div>
  </div>

产品.component.ts

export class ProductsComponent implements OnInit{

  products: Product[] = [];
  searchText = '';

  dataLoaded = false;
  constructor(private productService: ProductService, private activatedRoute: ActivatedRoute) { }

  ngOnInit(): void {
    this.activatedRoute.params.subscribe(params => {
      if(params["id"]){
        this.getProductsByCategoryId(params["id"])
      }else{
        this.getProducts();

      }
    })
  }

  getProducts() {
    this.productService.getProducts().subscribe(response => {
        this.products = response.data;
        this.dataLoaded = true; 
    })
   }

   getProductsByCategoryId(categoryId: number) {
    this.productService.getProductsByCategoryId(categoryId).subscribe(response => {     
        this.products = response.data;
        this.dataLoaded = true;
    })
   }  
}

我期望轻松地将数据从categoriesComponent传递到productsComponent

angular typescript parameter-passing webapi router-outlet
1个回答
0
投票

创建一个服务,确保你有

providedIn: 'root'
,这意味着整个应用程序都可以访问这个服务,需要添加到任何providers数组中。

从此服务设置和读取数据,以便轻松地将数据从任何组件传递到另一个组件!

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class ShareService {
  dataToShare = null;

  constructor() { }
}
© www.soinside.com 2019 - 2024. All rights reserved.