无法从JSON到Object的Observable映射工作

时间:2016-09-21 07:16:33

标签: json angular observable angular2-services

我在Angular2 beta 7中创建了一个应用程序,它从Web API中检索电影信息。这一切都运行良好,但现在我试图在Angular 2的最终版本中做同样的事情。除了将JSON信息映射到我自己的MovieInformation对象之外,我可以使大部分应用程序工作。

电影information.ts:

export class MovieInformation {
    constructor(
        public imdbID: number,
        public title: string,
        public year: number,
        public genre: string,
        public runtime: string,
        public poster: string,
        public director: string,
        public writer: string,
        public actors: string,
        public plot: string,
        public metascore: number,
        public imdbRating: number,
        public imdbVotes: number,
        public type: string,
        public favorite: boolean = false
    )
    {

    }
}

movie.service.ts

import {Injectable} from '@angular/core';
import { Http, Response } from "@angular/http";

import 'rxjs/Rx';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Rx';

import {Movie} from '../model/movie';
import {MovieInformation} from "../model/movie-information";

const searchMoviesUrl = (title) => `http://www.omdbapi.com/?s=${title}`;
const movieInformationUrl = (imdbId) => `http://www.omdbapi.com/?i=${imdbId}`;

@Injectable()
export class MovieService {
    constructor(private http:Http) {

    }

    ...

    getMovieInformation(movie:Movie): Observable<MovieInformation> {
        console.log(movieInformationUrl(movie.imdbID));
        return this.http.get(movieInformationUrl(movie.imdbID)).map(result => result.json())
        .map(m => new MovieInformation(m.imdbID, m.Title, m.Year, m.Genre, m.Runtime, m.Poster, m.Director,
                m.Writer, m.Actors, m.Plot, m.Metascore, m.imdbRating, m.imdbVotes, m.Type, movie.favorite))
            .catch(this.handleError);
    }

    private handleError(error: Response) {
        console.error(error);
        return Observable.throw(error.json().error || 'Server error');
    }
}

我要做的是映射JSON结果(http://www.omdbapi.com/?i=tt1245526):

{"Title":"RED",
"Year":"2010",
"Rated":"PG-13",
"Released":"15 Oct 2010",
"Runtime":"111 min",
"Genre":"Action, Comedy, Crime",
"Director":"Robert Schwentke",
"Writer":"Jon Hoeber (screenplay), Erich Hoeber (screenplay), 
Warren Ellis (graphic novel), Cully Hamner (graphic novel)",
"Actors":"Bruce Willis, Mary-Louise Parker, Heidi von Palleske, Karl Urban",
"Plot":"When his peaceful life is threatened by a high-tech assassin, 
former black-ops agent Frank Moses reassembles his old team in a last 
ditch effort to survive and uncover his assailants.",
"Language":"English, Russian",
"Country":"USA",
"Awards":"Nominated for 1 Golden Globe. Another 3 wins & 17 nominations.",
"Poster":"http://ia.media-imdb.com/images/M/MV5BMzg2Mjg1OTk0NF5BMl5BanBnXkFtZTcwMjQ4MTA3Mw@@._V1_SX300.jpg",
"Metascore":"60",
"imdbRating":"7.1",
"imdbVotes":"239,853",
"imdbID":"tt1245526",
"Type":"movie",
"Response":"True"}

使用 .map(m =&gt; new MovieInformation(...))到我自己的MovieInformation模型类中,但我无法让TypeScript编译器识别我的映射变量JSON,就像存在于JSON中的m.Title一样。

有人可以告诉我,我做错了导致这个问题吗?

1 个答案:

答案 0 :(得分:0)

我使用以下方法修复了它:

return this.http.get(movieInformationUrl(movie.imdbID)).map(result => result.json())
            .map((m: any) => new MovieInformation(m.imdbID, m.Title, m.Year, m.Genre, m.Runtime, m.Poster, m.Director,
            m.Writer, m.Actors, m.Plot, m.Metascore, m.imdbRating, m.imdbVotes, m.Type, movie.favorite))
        .catch(this.handleError);

虽然解决方案在于(m:any)将m定义为任何类型,因此编译器假设任何变量都可用,例如我的例子中的Title和Year。所以m:任何是我得到的JSON响应。

如果不输入m,编译器有时无法解析变量而无法启动应用程序。有了这个解决方案,这就解决了我的问题。