I have an array stored in one component and need to grant access to this array from another component that is not its parent or child. I am implementing routing to achieve this

I need to pass the 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
      }
    )
}

Is there an easy way for this component to receive that data?

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

  ngOnInit(): void {
  }

}

Answer №1

Utilize behavior subjects to simplify the process in this scenario.

Create a shared Service file that can be accessed throughout the application.

In the shared service file, implement the following:

@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;
}

}

Within your component, follow these steps:


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 >>>>>>

      }
    )
  }

}

To retrieve this data within another component, do the following:

    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;
           }
        });
      }
    
    }

This is how you can effectively use behavior subjects to manage data flow between components.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: Unable to inject HttpClient dependency. Angular 5

I recently switched to using the Angular template in Visual Studio 2017 and decided to update to Angular 5.2. However, I encountered an error while trying to make a http call from the service class. The error message I received is: https://i.sstatic.net/p ...

Enhance your Three.js development with TypeScript autocomplete

In my project using Node.js, Typescript, and Three.js, I have set up the commonjs syntax for module imports in my tsconfig.json file like this: { "compilerOptions": { "module": "commonjs" } } I installed Three.js via NPM and created a typescript ...

ngClass with multiple conditions

I am currently working on implementing the following functionality - I have two pre-set classes that are combined with some component variables successfully. However, I now need to include an additional conditional class. Although the first part is functi ...

Get rid of the Modal simply by clicking on the X mark

Objective: The modal should only be closed by clicking the X mark and not by clicking outside of it. Challenge: I am unsure how to resolve this issue when using the syntax code [config]="{backdrop: 'static'}" Additional Information: I am new ...

Unable to find the correct path in my NodeJS/Express/Typescript application

Having trouble with my '/api/users' route that doesn't seem to be properly defined in my routes setup. When attempting to access /api/users from the browser, it just sticks in a repeated loop. app.ts import * as express from "express" impo ...

Dealing with Firebase Range Queries Results

Hello, I am currently working on managing responses from a Firebase REST service as outlined in https://firebase.google.com/docs/database/rest/retrieve-data. Below is an example of the response I am getting: { "2": { "name": "John", "surname": " ...

Displaying numerical values in data labels for a donut chart using Highcharts

Currently, I have a donut highchart displaying names in the data labels. However, I need to show numbers instead. Can someone guide me on how to achieve this? This is my angular typescript code for the donut highchart: import { Component, OnInit, Input, ...

Observable emitting individual characters instead of the entire string in an optional parameter of an activated route

Within an Angular component, I have a method with the following content: this.route.paramMap.pipe( switchMap((params: ParamMap) => { let fooValue = params.get('selectedid'); console.log("inside switch map with value as " + ...

``The issue with the functionality of Angular animation stagger not performing correctly

I'm currently facing an issue with the new animation features in Angular 4.2, specifically the query and stagger functionalities. Anticipated behavior: I expect that when I click on the Toggle button, every element with the attribute [animate-bar] wi ...

How can I ensure the MatBottomSheet aligns perfectly with the top toolbar?

If we intend for the MatBottomSheet to appear with its top aligned perfectly against the top toolbar, what is the most effective approach to achieve this? Refer to the demo provided in the documentation. View the demonstration here In this stackblitz ex ...

The error message pops up when an Angular Library being utilized by another application encounters an issue: "Function calls are not supported in decorators but 'LoggerModule' was called"

I developed an Angular library with services to be utilized in various Angular applications. The functionality works smoothly without the --prod flag, indicating it works fine without Ahead-of-Time (AOT) compilation. However, when generating the library u ...

What is the best way to trigger a new api call after the previous one has successfully completed?

I'm just starting to learn about Angular and RxJS, and I have a specific scenario that I'm struggling with. I need to make a new API call after a previous one is successfully resolved within the Angular/RxJS context, but I'm not sure how to ...

Typical approach to receiving a transformed object from an HTTP service

One of the services I provide includes a method with the following implementation: public fetchCrawls(page: number): Observable<ICrawl[]>{ return this._http.get(this._crawlsURL + page) .map((res: Response) => { ...

Bidirectional binding in *ngFor with an Array of non-object elements

I have a straightforward array called tags = [];, and I am inserting a blank element into it when using the addNew() method like this: this.tags.push("");. This action creates an empty element inside the array. Currently, I am utilizing this array to dyna ...

How can I add an active class to the parent router in Angular when it has additional links attached to it?

Here is the code I am using to generate a menu for my demo project. It consists of 3 routers, as shown in this image. <li *ngFor="let item of items" class="nav-links__item" [ngClass]="{'nav-links__item-- ...

Tips for extracting specific information from a nested object in MongoDB

I am currently storing data for a NestJs based web application in MongoDB. My MongoDB data has the following structure: "gameId": "1a2b3c4d5e" "rounds": [ { "matches": [ { "match_id& ...

Ways to develop a dynamic Promise-returning Function

I find myself in a situation where I am aware of the type of data that will be returned when making a request to an API. Here is the function I have: const fetchData = async (url: string, options?: Object): Promise<any> => { const res = await f ...

Despite rebuilding, the content in the Angular application does not refresh upon making changes

My current project involves using ASP.Net core Web API as the backend with an Angular app on the frontend. I decided to customize my Angular project rather than using the default SPA template provided. To achieve this, I created a blank ASP.NET Core projec ...

- Tips for transferring single elements from one array to another array step by step

My array looks like ['N300W150727', '123test123', '123test1234'] and I want to push it into a MongoDB array. However, when I use $push, it adds the array inside another array. async updateSn(updateSn: UpdateSN) { const { ...

Trouble accessing route parameter in sub module with Angular 9

I'm encountering an issue while attempting to access route parameters within a nested module. Our application consists of two modules: Project and Ticket. The Project module serves as the main module, while Ticket acts as a sub module. The route I a ...