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