我试着在selected-movie类中添加电影,但我不明白我的代码有什么问题。

问题描述 投票:0回答:1

我有cart-movie.service.ts这个服务创建addMovies方法,用于在selected-movie类中添加电影,但我不明白我应该怎么做。

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

我确实在这里调用了服务,我不知道该给它什么参数

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');
  }
}
angular typescript shopping-cart
1个回答
1
投票

你的app.component.html并没有神奇地知道该方法在cartMoviesService服务中。它的工作原理和ts文件中的一样。试着添加它,这样它就能明白从哪里获取方法。

(click)="addMovies(movie)"

把它也改了

(click)"cartMoviesService.addMovies(movie)"

现在你应该可以使用创建的方法了 :)


0
投票

好吧,我改变了addMovies方法。

 addMovies(movie: Movies) { 
    this.cart.push(movie); console.log(movie);

}

现在我在我的控制台里有了对象:)

© www.soinside.com 2019 - 2024. All rights reserved.