Home > Software design >  in one component have an array. and want the other component to have access to this array. they aren
in one component have an array. and want the other component to have access to this array. they aren

Time:11-18

i want to pass addedToCart array from this component

export class ProductComponent implements OnInit {
  ***
  addedToCart: Item[] = [];
  constructor(private data: DataService) { }


  addToCart(product:Item){
  ***
}
  ngOnInit(): void {
    this.data.getData()
    .subscribe(
      response =>{
        this.products = response
      }
    )
  }

}

i want this component to get that data. is there any easy way?

    export class CartComponent implements OnInit {
      cartItems:Item[] | undefined;
      constructor() { }
    
      ngOnInit(): void {
      }
    
    }

CodePudding user response:

try looking into shared services and RxJS

CodePudding user response:

You can use behavior subjects to do the work for you in this case.

Create a common Service file to be used across the application.

In the common service file, you can do this:

@Injectable({
  providedIn: 'root'
})
export class CommonService {


initialValuesForProductsArray: string[] = [];

productsArraySource: BehaviorSubject<string[]> = new BehaviorSubject<string[]>(this.initialValuesForProductsArray);

productsArrayObservable: Observable<string[]> = this.productsArraySource.asObservable();

constructor() {}

setProductsArray(data: string[]) {
  this.productsArraySource.next(data);
}

getProductsArray(): Observable<string[]> {
  return this.productsArrayObservable;
}

}

Now in your component, do this:


export class ProductComponent implements OnInit {
  ***
  addedToCart: Item[] = [];
  constructor(
     private data: DataService,
     private commonService: CommonService <<<<<<<<<<< ADD THIS LINE >>>>>>>>
  ) { }


  addToCart(product:Item){
  ***
}
  ngOnInit(): void {
    this.data.getData()
    .subscribe(
      response =>{
        this.products = response;
        this.commonService.setProductsArray(this.products); <<<<<<< ADD THIS LINE >>>>>>

      }
    )
  }

}

In your component where you want to get this data, do this:

    export class CartComponent implements OnInit {
      cartItems:Item[] | undefined;
      constructor(private commonService: CommonService) {} <<<<< ADD THIS LINE >>>>
    
      ngOnInit(): void {
        <<<<<<<< ADD BELOW LINES >>>>>>>>
        this.commonService.getProductsArray().subscribe(data => {
           if (data && data.length) {
              this.cartItems = data;
           }
        });
      }
    
    }

thats how you use, behavior subjects to set, get data between components.

  • Related