Angular 5 从http请求中获取正确的Observable类型(为什么总是Observable<Object>?)

Angular 5 Get correct Observable type from http request (why is it always Observable<Object>?)

我在从 http.get 请求中获取正确的可观察类型时遇到了一些问题。这是我遇到问题的功能:

getMovie(title:string, year:number): Observable<Movie> {
    const params = new HttpParams()
        .set('title', title)
        .set('year', year.toString());
    return this.http.get(this.moviePath, {params})
  }

如您所见,我想使用参数 'title''year' 从我的后端 api 接收和观察 class Movie。问题是响应总是返回类型 Observable<Object> 而不是 Observable<Movie>.

我知道我可以创建一个新的 Movie 实例,并为其提供从列表中收到的属性。问题在于我的电影 class 具有可选的属性。这是我的电影 class:

export class Movie {
  title:string;
  year?:number;
  imdb?:string;
  trailer?:string;
  reviewClip?:string;
  reviewSummary?:string;
  reviewScore:number;
  createdAt?:Date;
  bestWeek:boolean;
  bestMonth:boolean;
}

有没有人知道一种简单的方法来使响应成为 Observable<Movie> 类型而不是 Observable<Object>

也许你可以尝试从 json 响应中进行类型转换。

一个例子

public getEmployees(): Observable<IEmployee[]> {  
        return this.http.get(this._repositoryURL)  
            .map((response: Response) =>

   { return <IEmployee[]>response.json() })  
            .catch(this.handleError);  
 }  

您的代码

getMovie(title:string, year:number): Observable<Movie> {
    const params = new HttpParams()
        .set('title', title)
        .set('year', year.toString());
    return this.http.get(this.moviePath, {params}).map((response: Response) => { return <Movie>response.json() })  
                .catch(this.handleError);
 }

 private handleError(errorResponse: Response) {  
        console.log(errorResponse.statusText);  
        return Observable.throw(errorResponse.json().error || "Server error");  
 } 

If you are using HttpClient & Http,It will return you automatically Observable.

所以修改你的代码为

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable'
import { HttpClient,HttpHeaders,HttpResponse,HttpParams } from '@angular/common/http';

import { environment } from '../../../../environments/environment';
import { Movie } from '../models/movie'


@Injectable()
export class MovieService {

  constructor(private http:HttpClient) {

   }

  getMovie(title:string, year:number) {
    const params = new HttpParams()
        .set('title', title)
        .set('year', year.toString());
    return this.http.get<Movie>(this.moviePath, {params})
  }
}

This will give you response of type Movie