Home > Software engineering >  Shared data between Angular componets not displayed after click event
Shared data between Angular componets not displayed after click event

Time:01-24

I want that in my angular app an array of products productCategory is shared beetween component1 and component2 (the two components don't have any relation) after a click event that occurs in component1. I tried to achieve this goal creating a service in this way:

import { Injectable } from '@angular/core'; 
import { Product } from '../product';

@Injectable({   providedIn: 'root' }) 
export class SharedService {   
  productsCategory: Product[]=[];

  constructor() { }

  setProductCategory(data: Product[]){
    this.productsCategory=data;   }

  getProductCategory(){
    return this.productsCategory;   } }

But when the click event occurs nothing is displayed on the browser page, the array is only printed out on the browser console.

This is the click event in the html code of component1:

<mat-menu #makeup="matMenu">
    <button mat-menu-item (click)="categoryFilter('Make-up eyes')" routerLink="/products/searchProduct/by_category"  routerLinkActive="active">Eyes</button>
    ...
</mat-menu>

component1.component.ts

 export class Component1 implements OnInit {
      public productCategory: Product[]=[];
      displayedColumns = ['name', 'description', 'price']
      constructor(private  shared: SharedService,private productService: ProductService){}
    
      ngOnInit():void {
    
      }
    
      public categoryFilter(category: string): void{
        this.productService.getProductsByCategory(category).subscribe(
          (response: Product[]) => {
            this.productCategory=response;
            this.shared.setProductCategory(this.productCategory);
            console.log(response);
    
          },
          (error: HttpErrorResponse)=>{
            alert(error.message);
          }
        )
      }
    }

component2.component.ts:

    export class Component2 implements OnInit {
      public productCategory: Product[]=[];
      displayedColumns = ['name', 'description', 'price']
      constructor(private shared: SharedService
      ) { }
    
      ngOnInit(): void {
        this.productCategory=this.shared.getProductCategory();
    
      }
    }

component2.component.html:

<table mat-table [dataSource]="productCategory"  >


  <ng-container matColumnDef="position">
    <th mat-header-cell *matHeaderCellDef> No. </th>
    <td mat-cell *matCellDef="let productCategory"> {{productCategory.position}} </td>
  </ng-container>


  <ng-container matColumnDef="name">
    <th mat-header-cell *matHeaderCellDef> Name </th>
    <td mat-cell *matCellDef="let productCategory"> {{productCategory.name}} </td>
  </ng-container>


  <ng-container matColumnDef="description">
    <th mat-header-cell *matHeaderCellDef> Description </th>
    <td mat-cell *matCellDef="let productCategory"> {{productCategory.description}} </td>
  </ng-container>


  <ng-container matColumnDef="price">
    <th mat-header-cell *matHeaderCellDef> Price </th>
    <td mat-cell *matCellDef="let productCategory"> {{productCategory.price}} </td>
  </ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>

CodePudding user response:

Use observables instead of getters:

 export class SharedService {   
  private productsCategory: new BehaviorSubject<Array<Product>>([]);

  public productsCategory$:Observable<Array<Product>> = this.productsCategory.asObservable()

  constructor() { }

  setProductCategory(data: Product[]){
    this.productsCategory.next(data);   }

Subscribe to the public observable in your components

  •  Tags:  
  • Related