0
我创建了一个简单的Angular2应用程序来从外部web api获取电影列表(http://www.omdbapi.com/?s= $ {keyword})。我在我的应用程序中获得结果,但不是我想要的结果。如何将我的Angular2模型映射到json web api结果
我想将返回的json映射到我的MovieService中的Movie模型。
这是我有:
这个模型看起来像这样(movie.model.ts):
export class Movie {
constructor(
public Title:string,
public Year:string,
public imdbID:string,
public Type:string,
public Poster:string
){ }
}
movie.service.ts
// movie.service.ts
import { Injectable } from '@angular/core';
import { Movie } from '../models/movie.model';
import { Http } from '@angular/http';
import 'rxjs/Rx';
const makeUrl = (keyword) => `http://www.omdbapi.com/?s=${keyword}`;
@Injectable()
export class MovieService {
constructor(private http:Http){
}
searchMovies(keyword)
{
return this.http.get(makeUrl (keyword))
//.map(res => <Movie[]> res.json());
.map(res => res.json())
//.map(movies => <Movie[]> movies.Search);
.map(movies => movies.Search);
}
}
下面的应用程序。组件:
import { Component } from '@angular/core';
import { Movie } from './models/movie.model';
import { HTTP_PROVIDERS } from '@angular/http';
import {MovieService} from "./services/movie.service";
@Component({
selector: 'my-app',
templateUrl: 'app/app.component.html',
providers : [MovieService, HTTP_PROVIDERS]
})
export class AppComponent {
public movies:Movie[] = [];
public title:string = "My super movies!";
constructor(private movieService:MovieService) {
}
searchMovies(keyword) {
this.movieService.searchMovies(keyword)
.subscribe(movieData => {
this.movies = movieData; // 1. success handler
},
err => console.log(err), // 2. error handler
()=> console.log('Getting movies complete...') // 3. complete handler
)
}
}
Th是我app.component.html
<!-- app.component.html -->
<div class="row">
<div class="col-md-6">
<h1>Movies via OMDb API</h1>
<div>
<input type="text" #keyword class="input-lg" placeholder="movie name...">
<button class="btn btn-primary" (click)="searchMovies(keyword.value)">Find movies</button>
</div>
<table class="table table-striped">
<tr>
<th>Naam</th>
<th>Jaar</th>
<th>Poster</th>
</tr>
<tr *ngFor="let movie of movies">
<td>{{ movie.Title }}</td>
<td><span class="movieYear">{{ movie.Year}}</span></td>
<td><img src="{{movie.Poster}}" alt="Movie" class="moviePoster"/></td>
</tr>
</table>
</div>
</div>
这是main.ts
import { bootstrap } from '@angular/platform-browser-dynamic';
import { HTTP_PROVIDERS } from '@angular/http';
import { AppComponent } from './app.component';
bootstrap(AppComponent, [HTTP_PROVIDERS]);
应用的package.json,systemjs.config.js,tsconfig.json和typings.json都从QuickStart tutorial on Angular.io