I attempted to include a movie in the selected-movie class, but I'm baffled by the issues in my code

I'm working on a service called cart-movie.service.ts which has a method called addMovies for adding movies to the selected-movie class. However, I'm having trouble figuring out how to implement this.

app.component.html

<div class="col-2" *ngFor="let movie of moviesList" (click)="addMovies(movie)">
      <div class="movie">
        {{ movie.attributes.title }}
        <img [src]="movie.thumbnails.small">
        <p><strong>Duration:</strong> {{ movie.attributes.duration | formatime}}mn</p>
        <div class="details">
          <p><strong>Director:</strong><br> {{ movie.attributes.director }}</p>
          <p><strong>the actors:</strong><br>{{ movie.attributes.actors }}</p>
          <p><strong>the release year:</strong><br>{{ movie.attributes.year }}</p>
        </div>
      </div>
    </div>
  </div>

  <div class="row">
    <h1 class="col-12">
      Movies Selected
    </h1>
    <div class="col-12 selected-movie">
    </div>
  </div>

app.component.ts

    import { Component, OnInit } from '@angular/core';
import { MoviesService, Movie } from './shared/services/movies.services';
import { CartMoviesService } from './shared/services/cart-movies.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})

export class AppComponent implements OnInit {

  title = 'app-entretien';
  moviesList: Movie[];
  moviesSelected: Movie[];

  currentPage: number = 0;

  constructor(private moviesService: MoviesService, private cartMoviesService: CartMoviesService) {
  }

  ngOnInit() {
    this.moviesService.getList(1, 20).subscribe(data => {
      this.moviesList = data.content;
    });
    this.cartMoviesService.addMovies(this.movie);
  }

I have attempted to call the service in the code above but am unsure about what argument to pass it.

cart-movies.service.ts

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

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

  public cart = [];
  movie: any;

  constructor() { }

  addMovies(movie) {
    this.cart.push(movie);
    alert(movie + 'was added to cart');
  }
}

Answer №1

It is important to remember that your app.component.html does not automatically know the location of the method in the cartMoviesService service. You need to specify it just like you would in the ts file. Make sure to add the necessary information for the method to work:

(click)="addMovies(movie)"

Update it to include the reference to the cartMoviesService:

(click)"cartMoviesService.addMovies(movie)"

After making this change, you should now be able to utilize the newly created method.

Answer №2

Alright, I made some adjustments to the addMovies method,

 updateCart(movie: Movie) { 
    this.cart.push(movie); console.log(movie);

}

Now, if you check your console, you should see the added movie object :)

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

Using the locale identifier en-GB can lead to date formats being displayed incorrectly

I'm struggling with setting up the correct locales in my Angular application. As per the documentation, I've inserted the following code snippet into my angular.json file. "projects": { "appname": { ..., "i18n&q ...

Dialog box obscuring PrimeNG dropdown menu

I'm working on an Angular2 app that utilizes PrimeNG components. My issue arises when trying to include a dropdown inside a dialog box. Despite my implementation, the dropdown ends up being cut off due to the constraints of the dialog box, as visible ...

Learn how to trigger an event or API call in Angular 8 when the browser is closed with the help of HostListener

I am facing the challenge of calling a simple websocket closure API when the browser is closed in my project. I attempted to utilize HostListener, but unfortunately it did not work as expected. You can find the code snippet below: https://stackblitz.com/ ...

The icon for caret down in FontAwesome is not displaying when using ngClass

I am experiencing an issue where only the fontawesome caret up is displayed when sorting a field, but the fontawesome caret down is not showing. I have provided the code snippet below. HTML <th (click)="sort('ref')">Ref {{reverse}} & ...

What is the best way to adjust the Material Drawer width in Reactjs to match the width of its children?

Currently, I am utilizing the Material-ui Drawer component to toggle the display of content on the right side of the screen. The functionality I am aiming for is that when the Drawer opens, it will shrink the existing content on the right without any overl ...

Angular dynamic array binding binds to multiple elements rather than just one

In my code, I am working with an array object structured as follows: let myArray=[ { "id":"100", "child1":[ {"id":"xx","Array":[]}, {"id":"yy","Array":[]}, {"id":"zz","Array":[]} ] }, { "id":"200", "child1":[ {"id":"xx","Array ...

Nested validation schema featuring conditional validation - yes, we've got it covered!

In my Formik object, I have set initial values as follows: {customerDetails: {id: "", name: "", mobileNumber: ""}, notes: {id: "", text: "", type: ""}} How can I create a conditional Yup validati ...

Error in file @angular/service-worker/src/module.d.ts at line 30, character 9: The type 'ModuleWithProviders' is not a generic type

https://i.sstatic.net/01bwW.pngI have successfully integrated "angular-push-notifications" into my angular-4 project by following the instructions from the link below: I have configured the "Service Workers" as shown below 1. Install the package using np ...

Encountering an issue upon launching the application: "Error: Token is required in order to proceed!"

I encountered the following error. Can someone please point out what's causing it? How can I resolve this issue? Could there be something missing in main.ts? Error: (index):39 Error: Error: Token must be defined! at new BaseException (https:/ ...

The function doc.fromHTML is not recognized in Angular 6

I am having trouble exporting an HTML template to a PDF using the jsPDF library with Angular. I keep getting the error message "doc.fromHTML is not a function." import { Component, ViewChild, ElementRef } from '@angular/core'; import * as jsPDF ...

Exploring the various methods of setting up a Create React App project with TypeScript

One of my old books from a year ago mentioned... npx create-react-app XXX --typescript But looking at the current Create React App documentation, it says... npx create-react-app XXX --template typescript They both seem to yield the same result. Is ther ...

Display the length of the product array when I have multiple JSON objects

I am working with the following JSON data: { "StatusCode": 0, "StatusMessage": "OK", "StatusDescription": [ { "_id": "12123", "dateCreated": "2019-12-03T13:45:30.418Z", "pharmacy_id": "011E7523455533 ...

Best location for the classes of the Domain Model suggested

Currently, I am delving into Angular 2 and making use of angular-cli for creating components and services. Adhering to the directory structure suggested by angular-cli (view screenshot below), I am uncertain about where to include domain model objects like ...

Angular 2 TypeScript: The concat() function operates as mutable within the framework

When I declare an array on an @Injectable provider, my intention is to use it across different components. normeList: any[] = [ { name: 'choice 1', type:'false' }, { name: 'choice 2', typ ...

Angular Material's present day button

I've been tasked with adding a "Today" button to an Angular datepicker popup that selects the current date and closes the popup). <input matInput [matDatepicker]="toPicker" formControlName="validTo" > <mat-datepicker-toggl ...

Set theme value for the tab group in Angular Material

Trying to change the tab theme in Angular Material by setting it directly seems to be a bit tricky. The example from Angular Material shows how to do it with a toggle button, but when I try to code it directly, it doesn't work. Here's the code sn ...

What is the process for refreshing the component content in Angular 2?

There was a moment during execution when my URL had the following appearance: http://localhost:4200/personal/51c50594-a95c-4a18-ac7b-b0521d67af96 I desire to visit a page with a different GUID and different content. http://localhost:4200/personal/{other ...

A guide on fixing the issue of the missing X-Frame-Options header in Angular

I'm currently working on an Angular-14 project. One challenge I'm facing is: The X-Frame options are missing - The X-Frame-Options header is either not set or set improperly to DENY or SAMEORIGIN. This can leave the application vulnerable to c ...

Which is better for dynamically presenting data: Angular2, React, or plain jQuery?

As someone relatively new to the world of web development, I am eager to explore the different technologies available that facilitate the following functionalities: Displaying user-specific data from a database without requiring page refresh Filtering da ...

When sending an http.post request in Angular 2, the req.body parameter may sometimes

I'm currently facing an issue with my Angular 2 application. I'm attempting to send JSON objects to my MongoDB database. When I click the "post" button, it successfully sends the _id to my MongoDB, but my req.body remains empty. import { Inj ...