сохранить и получить на firebase в угловых не работает - PullRequest
0 голосов
/ 27 января 2019

Почему мой компонент фильма не обновляется после получения данных.Также не сохранять данные, если я добавил новый фильм или внес изменения в существующие фильмы.

Это просто сохранение и выборка данных, записанных в файле movie.service.ts.Также извлеченные данные не отображаются на компоненте фильма.

Data-storage.service

import { Injectable } from '@angular/core';
import { MovieService } from '../movies/movies.service';
import { HttpClient, HttpHeaders, HttpParams, HttpRequest } from '@angular/common/http';
import { Movie } from '../movies/movie.model';
import { Observable} from 'rxjs';
import { map } from 'rxjs/operators';
// import 'rxjs/Rx';
// import 'rxjs/Rx';

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

  constructor(private httpClient: HttpClient,
    private movieService: MovieService,) { }

  storeMovies(): Observable<any> {
    const req = new HttpRequest('PUT', 'https://moviepedia-4211a.firebaseio.com/movies.json', this.movieService.getMovies(), {reportProgress: true});
    return this.httpClient.request(req);
  }

  getMovies() {
    this.httpClient.get<Movie[]>('https://moviepedia-4211a.firebaseio.com/movies.json', {
      observe: 'body',
      responseType: 'json'
    })
      .pipe(map(
        (movies) => {
          console.log(movies);
          return movies;
        }
      ))
      .subscribe(
        (movies: Movie[]) => {
          this.movieService.setMovies(movies);
        }
      );
  }
}

movie.service.ts:

import { Injectable } from '@angular/core';
import {Subject} from 'rxjs';
import { Movie } from './movie.model';

@Injectable()
export class MovieService {
    moviesChanged = new Subject<Movie[]>();

    private movies: Movie[] = [
        new Movie(
            'Movie test', 'Movie details', 'https://s18672.pcdn.co/wp-content/uploads/2018/01/Movie-300x200.jpg'
        ),
        new Movie(
            'Movie test 2', 'Movie details 2', 'https://s18672.pcdn.co/wp-content/uploads/2018/01/Movie-300x200.jpg'
        ),
        new Movie(
            'Movie test 2', 'Movie details 3', 'https://s18672.pcdn.co/wp-content/uploads/2018/01/Movie-300x200.jpg'
        )
    ];

    constructor(){}

    getMovie(index: number) {
        return this.movies[index];
    }

    getMovies() {
        return this.movies.slice();
    }

    addMovie(movie: Movie) {
        this.movies.push(movie);
        this.moviesChanged.next(this.movies.slice());
    }
    
    updateMovie(index: number, newMovie: Movie) {
        this.movies[index] = newMovie;
        this.moviesChanged.next(this.movies.slice());
    }

    deleteMovie(index: number) {
        this.movies.splice(index, 1);
        this.moviesChanged.next(this.movies.slice());
    }

    setMovies(movies: Movie[]) {
        this.movies = movies;
        this.moviesChanged.next(this.movies.slice());
    }
}

movie.model.ts

export class Movie {
    public name: string;
    public description: string;
    public imagePath: string;
  
    constructor(name: string, description: string, imagePath: string) {
      this.name = name;
      this.description = description;
      this.imagePath = imagePath;
    }
  }
  

movie.component:

import { Component, OnInit, EventEmitter, Output, OnDestroy } from '@angular/core';
import { Movie } from '../movie.model'
import { MovieService } from '../movies.service';
import { Router, ActivatedRoute } from '@angular/router';
import { Subscription } from 'rxjs';

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

  constructor(private movieService: MovieService,
    private router: Router,
    private route: ActivatedRoute) { }

  ngOnInit() {
    this.subscription = this.movieService.moviesChanged
    .subscribe(
      (movies: Movie[]) => {
        this.movies = movies;
      }
    );
  this.movies = this.movieService.getMovies();
  }

  onNewMovie() {
    this.router.navigate(['new'], {relativeTo: this.route});
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

Что я могу сделать, чтобы сохранить и извлечь данные, которые будут отображаться на странице.

1 Ответ

0 голосов
/ 27 января 2019

Я думаю, что проблема с вашим запросом PUT заключается в том, что используемый вами URL-адрес ожидает json, но вы отправляете объект Movie.Вы должны отправить и получить json на этот URL.

желаю, чтобы это помогло ...

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...