我是Angular的新手,正在尝试构建一个电影应用。
我想从我本地计算机上的JSON文件中获取数据。我可以在MovieListComponent中显示JSON文件中的所有电影。但是当用户单击特定影片的视图细节时,我无法在MovieDetail组件中显示数据。
MovieListComponent.ts
import {Component ,OnInit} from '@angular/core';
import {MovieService} from '../services/movie.service';
import {Router} from '@angular/router';
import {Movie} from '../movie';
@Component({
moduleId:module.id,
templateUrl: 'search.html',
})
export class MovieListComponent implements OnInit {
movies:Movie[];
constructor(
private _movieservice:MovieService,
private router:Router ){
}
getMovies():void{
this._movieservice.getMovies().then(movies => this.movies = movies);
}
ngOnInit(){
this.getMovies();
}
onSelect(movie:Movie):void{
this.router.navigate(['/movies',movie.id]);
console.log(movie.title);
}
}
MovieDetailComponent.ts
import {Component,OnInit} from '@angular/core';
import {ActivatedRoute,Params} from '@angular/router';
import {Location} from '@angular/common';
import 'rxjs/add/operator/switchMap';
import {MovieService} from '../services/movie.service';
import {Movie} from '../movie';
@Component({
template:`<div *ngIf="movie">
{{movie.title}}
<h4>You're seleted departmentId is = {{movie.id}} </h4>
</div>`
})
export class ViewDetailComponent implements OnInit{
movie:Movie;
constructor(
private route:ActivatedRoute,
private movieservice:MovieService,
private location:Location){}
ngOnInit():void{
this.route.params
.switchMap((params:Params) => this.movieservice.getMovie(+params['id'] ))
.subscribe(movie => this.movie = movie);
}
}
MovieService.ts
import{Injectable} from '@angular/core';
import {Http} from '@angular/http';
import {Movie} from '../movie';
import 'rxjs/add/operator/toPromise';
@Injectable()
export class MovieService{
private movieUrl = './app/movies.json';
constructor(private _http:Http){
console.log('Movie Service up and running');
}
getMovies():Promise<Movie[]>{
return this._http.get(this.movieUrl)
.toPromise().then(res => res.json() as Movie[]);
//.map(res => res.json());
}
getMovie(id: number):Promise<Movie>{
// const url = `${this.movieUrl}/${id}`;
return this._http.get(this.movieUrl)
.toPromise().then(res => res.json() as Movie)
}
}
答案 0 :(得分:6)
如果您使用Angular-CLI
,则需要将json文件添加到assets文件夹。然后从那里参考。
如果不是,您必须确保您的Web服务器正在提供json文件并从那里使用。
答案 1 :(得分:0)
您的问题是您将movies.json投射到一部电影:
getMovie(id: number):Promise<Movie[]>{
return this._http.get(this.movieUrl)
.toPromise().then(res => res.json() as Movie[] /* Error here */)
}
相反,你需要获得一部电影,或搜索电影并返回一个具有给定ID的电影:
getMovie(id: number):Observable<Movie>{
return this._http.get(this.movieUrl)
.map(response => { return <Movie>(<Movie[]>response.json())
.find((item: Movie) => item.id == id));
}