I attempt to transfer information from one of my components to another component

Why am I unable to display the data from the main component in the payment component?

Solution

export class BookListService {

  url: string = 'http://henri-potier.xebia.fr/books';

  item:any=[];

  public book: Book[];

  constructor(private http: HttpClient) { }

  getBookList(): Observable<Book[]> {
    return this.http.get<Book[]>(this.url);
  }

  addToBook() {
    this.item.push(this.book);
  }

}

payment.component.ts

export class PaymentComponent implements OnInit {

  public book: Book;
  addedBook: any = [];

  constructor(private bookListService: BookListService) { }

  ngOnInit(): void {
    this.addedBook = this.bookListService.getBookList();
  }

}

payment.html

<div *ngFor="let book of addedBook">
    <span>{{ book.title }}</span>
    <span>{{ book.price | currency }}</span>
</div>

main.component.ts

export class MainComponent implements OnInit {

  bookList: any = [];

  constructor(private bookListService: BookListService) { }

  ngOnInit(): void {
    this.bookListService.getBookList().subscribe(data => {
      this.bookList = data
    })
  }

  addButton() {
    this.bookListService.addToBook()
    alert('item added');
  }

}

main.component.html

  <div class="grid-container">
    <div class="wrapper" *ngFor="let book of bookList" class="form-group">
        <div class="product-img">
            <img [src]="book.cover" alt="livre" height="420" width="327">
        </div>
        <div class="product-info">
            <div class="product-text">
                <h2>{{book.title}}</h2>
                <p>{{book.synopsis}}</p>
            </div>
            <div class="product-price-btn">
                <p>{{book.price | currency: 'EUR'}}</p>
                <button type="button" (click)="addButton()">buy now</button>
            </div>
        </div>
    </div>
</div>

interface

export interface Book {
    title: string;
    price: number;
    cover:string;
    synopsis:string;
}

Answer №1

Both components are utilizing the same function that returns an Observable. To display data in your payment component, you can utilize the async pipe or subscribe again.

If using async pipe: payment.html

<div *ngFor="let item of addedItems | async">
    <span>{{ item.name }}</span>
    <span>{{ item.price | currency }}</span>
</div>

Alternatively, you have direct access to all items added through the service:

this.addedItems = this.itemService.items;

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

What is the proper way to send a list as a parameter in a restangular post request

Check out this code snippet I found: assignUserToProject(pid: number, selectedUsers: any, uid: number) { let instance = this; return instance.Restangular.all("configure/assign").one(pid.toString()).one(uid.toString()).post(selectedUsers); } ...

Developing a versatile table component for integration

My frontend app heavily utilizes tables in its components, so I decided to create a generic component for tables. Initially, I defined a model for each cell within the table: export class MemberTable { public content: string; public type: string; // ...

Exploring the dynamic changes in user authentication state with Angular Fire subscriptions

At the moment, I have been listening to authentication state changes in my ngOnInit method of my AppComponent: export class AppComponent implements OnInit { constructor(public fireAuth: AngularFireAuth) { } ngOnInit(): void { this.fireAuth.auth ...

Is there a way to retrieve the operating system user name using Angular 6?

In order to ensure security for hospital staff using our app on Chromebooks, I am looking to retrieve the OS username and send it to a .NET web API. This API will then check if the user exists in the active directory and return their information. ...

Enum-centric type guard

Could I create a custom type guard to verify if a specified string is part of a specific string enum in a more specialized way? Check out the following example: enum MyEnum { Option1 = 'option one', Option2 = 'option two', } const ...

Leveraging environment variables in NextJS - passing values to the client side

I'm facing a frustrating issue with my project in server mode. We need to pass environment variables at runtime and access them on both the server and client side. Following the publicRuntimeConfig method from the documentation, everything works fine ...

What makes an Angular project different from conventional JavaScript projects that prevents it from running in a browser like any other?

When attempting to run index.html from the dist folder in the browser, I encountered issues. This is different from an AngularJS application where simply importing the script file into index.html allows the application to work seamlessly. Why is it not po ...

The promise callback in Angular2 is unable to access this

This snippet of code is quite odd, but it resides within a service context: constructor() { gapi.load('client:auth2', this.loadGoogleApi); } private loadGoogleApi() { // Array of API discovery doc URLs for APIs used by the quickstart ...

The error message received is: `npm ERR! code ERR_TLS_CERT_ALTNAME_INVALID

Setting up a new Angular app after working on an existing one for months was quite challenging. Today, while trying to install the new Angular app through the terminal on my Mac, the process was unusually slow and ended up showing this error: npm ERR! co ...

What is the best way to extract data from multiple FormControl instances using RxJS in Angular?

I am currently subscribed to three FormControl instances named filter1, filter2, and filter3. My goal is to fetch the values of all three whenever any one of them changes. I initially attempted to achieve this using combineLatest, but found that it only em ...

The issue of assigning a file as a prop in React TypeScript: ("True" type cannot be assigned to "ChangeEventHandler<HTMLInputElement>")

I'm currently developing an application using reactjs My goal is to implement a feature that allows file uploads passed as a prop from a child component to a parent component Child Component const RegisterIndividual: React.FC< { upload_id_card: R ...

Whenever I try to run npm start within my angular component, I encounter a compilation problem

I am currently working on dynamically rendering a component on one of my screens. To achieve this, I am utilizing the componentFactoryResolver.resolveComponentFactory and viewContainerRef.createComponent APIs. I have declared the variable "loadedComp : Glo ...

Sorting items in Ag-Grid according to user's preference

Here is an example of a header in ag-grid with custom sorting applied: { headerName: "StudentId", field: "StudentId", width: 140, editable: false, enableRowGroup: true, comparator: (valA, valB, n1, n2, inver ...

How can I call a method from a class using Typescript when getting an error saying that the property does not exist on the

Below is a service definition: export class MyService { doSomething(callbacks: { onSuccess: (data: Object) => any, onError: (err: any) => any }) { // Function performs an action } } This service is utilized in a component as shown be ...

Error encountered while trying to import a bootstrap file into a component

I am facing an issue in my Angular project where I have locally downloaded Bootstrap and trying to reference the _variables.scss file inside a component. However, whenever I import it into the component, I encounter a compile error. Is there a mistake in m ...

How can Angular send datetime data to Nodejs in the most effective manner?

Working with the primeng calendar component within a template-driven form, I encountered an issue. When passing the date 16/05/2018 11:45 from Angular to Node, it gets converted to 2018-05-16T06:15:33.000Z. I discovered that I could convert it back to IST ...

Ways to retrieve "this" while utilizing a service for handling HTTP response errors

I have a basic notification system in place: @Injectable({ providedIn: 'root', }) export class NotificationService { constructor(private snackBar: MatSnackBar) {} public showNotification(message: string, style: string = 'success' ...

What is the method for adding attributes to a class dynamically in TypeScript so that they can be accessed by instances?

I attempted to create a universal factory function that generates custom enum objects, but the instances were not able to retrieve the correct properties. Take a look at the preview of the code online: https://stackblitz.com/edit/typescript-rkl1zr Workin ...

angular2 - Having trouble retrieving data from subject

Why am I unable to successfully initialize and retrieve data from a service using a subject in Angular? HomeComponentComponent.TS export class HomeComponentComponent implements OnInit { public homeSub; constructor( private subService: SubjectServ ...

"Exploring Angular with Storybook: Enhancing Components with NgControl

Having created the following Class : export class TestComponent implements OnInit, ControlValueAccessor { constructor( @Optional() @Self() public ngControl: NgControl) { if (ngControl) { ngControl.valueAccessor = this; } } I am now in ...