使用* ngFor?中的角度显示将新对象添加到我的页面中?

时间:2019-01-31 08:33:20

标签: html angular api

我想向页面添加一个新的电影对象,使其像我从api中获得的其他对象一样(带有文本和按钮,如下图所示),并且在重新加载页面时不再能看到它们。

我真正想做的是,当我单击“添加电影”按钮时,获得一个模态,将其填充并将其添加到我的页面中,就像我得到的其他电影一样。

请在下面检查我的代码...

data.service.ts

import { Observable, of, throwError } from 'rxjs';
import { Movie } from './model/movie.model';
import {catchError, tap, map} from 'rxjs/operators';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';


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

  private MOVIES: Movie[] = [
    {imdbID:"1", Title: 'Avatar', Year: 2009, Director: 'James Cameron', Genre:'Fiction', Runtime: '176min'},
  ];

  constructor(private http: HttpClient) { }


  getMovies() {
    return fetch('https://www.omdbapi.com/?s=batman&apikey=9fa6058b')
    .then(function (resp) {
      return resp.json()
    });
  }

  getMovieById(imdbID:string) {
    return this.http.get<Movie[]>(imdbID);
  }


  updateMovie(movie:Movie) {
    return this.http.put(movie.imdbID, movie);
  }

  createMovie(movie:Movie) {
    return this.http.post('', movie);
  }
}

movie-list.component.ts

import { Router } from '@angular/router';
import { DataService } from './../data.service';
import { Movie } from './../model/movie.model';
import { Component, OnInit } from '@angular/core';


@Component({
  selector: 'app-movie-list',
  templateUrl: './movie-list.component.html',
  styleUrls: ['./movie-list.component.css']
})
export class MovieListComponent implements OnInit {

  movies: Movie[];

  constructor(private dataService:DataService, private router: Router){}

  ngOnInit() {

    this.dataService.getMovies()
      .then(res => this.movies = res.Search);
  }

  addMovie() {
    this.movies.push(new Movie())
  }
}

add-movie.component.ts

import { Movie } from './../model/movie.model';
import { Router } from '@angular/router';
import { DataService } from './../data.service';
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-add-movie',
  templateUrl: './add-movie.component.html',
  styleUrls: ['./add-movie.component.css']
})
export class AddMovieComponent implements OnInit {

  movies:Movie[];

  constructor(private formBuilder:FormBuilder, private dataService:DataService, private router: Router) { }

  addForm: FormGroup;

  ngOnInit() {
    this.addForm = this.formBuilder.group({
      imdbID: [],
      Title: ['', Validators.required],
      Year: ['', Validators.required],
      Director: ['', Validators.required],
      Genre: ['', Validators.required],
      Runtime: ['', Validators.required]
    });
  }

  onSubmit() {
      // this.movies.push(this.addForm.value);
      this.dataService.createMovie(this.addForm.value)
      .subscribe( data => {
        this.router.navigate(['movie-list']);
      });
    }

movie-list.component.ts

h3>List of Movies:</h3>


<div class="card" *ngFor="let movie of movies">
  <div class="card-header">
    <img class="card-img-top" src="{{movie.Poster}}" alt="Card image cap">
  </div>
  <div class="card-body">
    <h4 class="card-title">{{movie.Title}}</h4>
    <h4>{{movie.Year}}</h4>
  </div>
  <div class="card-footer">
    <button type="button" class="btn btn-success" data-toggle="modal" data-target="#editModal">Edit</button>
    <button type="button" class="btn btn-success" (click)="deleteMovie(movie.imdbID)" >Delete</button>
  </div>
</div>

模态打开时,填写所有内容并将电影添加到我的电影列表中。 问题是正在播放的电影已经来自一个api,所以我如何不在api上而是在页面本身上添加电影?

enter image description here

enter image description here

2 个答案:

答案 0 :(得分:0)

我在这里进行了一次堆叠闪电射击:https://stackblitz.com/edit/angular-c7q9xp

但是使用数组作为内存存储仅应用于培训目的。在真实的应用程序中,您应该真正使用自己的数据库实现后端api。

编辑:

要从代码中添加电影,请在您的Submit方法中完成:

 onSubmit() {
     const movie = this.addForm.value as Movie;
     // you need to generate a uuid for every new entry
     movie.imbdID = uuid.v4();
     crudService.add(movie);
    }

答案 1 :(得分:0)

我已经在stackblitz上看到了您的代码,并发现您需要对现有代码进行一些更改才能使其正常运行。以下是您需要的更改。

  1. 您需要使用FormsModule, ReactiveFormsModuleapp.module.ts中的import { FormsModule, ReactiveFormsModule} from '@angular/forms';的角度形式导入movie-list.component.ts并将这些导入放置在您的AppModule导入数组中

  2. 在您的this.dataService.getMovies().then(res => this.movies = res.Search);中,注释这段代码 data.service.ts来自ngOnInit方法。因此,您将不会看到API中的电影,而只会看到您在getAll()中声明的电影(头像)。

  3. data.service.ts中的add-movie.component.html方法中删除slice方法。

  4. 在您的(ngSubmit)中,无法触发type="submit"事件。因此,您需要将[formGroup]="addForm"添加到“添加按钮”。 另外,您需要将括号添加为new Vue({ render: h => h('div', { className: 'preview' }, ['Hello World']) }).$mount('#vue-preview').$destroy()

通过上述更改,添加电影时,您可以在电影列表中看到它的渲染。

找到这些确实需要一些时间。请让我知道他们是否为您工作。

所有这些仅用于您的测试目的。如果要将电影放到API上,则需要将其发布到API。

我什至编辑了您的stackblitz代码,但无法将其放在此处。

希望您发现它有用。