类型'Subscription'不能分配给'Observable <SearchResult []>'Angular 5使用HttpClient而不是Http

Isa*_*eur 9 observable angular

我正在尝试使用新的HttpClient类而不是旧的Http.

我想映射我从subscribe方法获得的数据,但得到以下错误.关于我为何得到这个的任何建议?

码:

export class YoutubeSearchService {
  constructor(
    private http: HttpClient,
    @Inject(YOUTUBE_API_KEY) private apiKey: string,
    @Inject(YOUTUBE_API_URL) private apiUrl: string,
  ) { }

  search(query: string): Observable<SearchResult[]> {
    const params: string = [
      `q=${query}`,
      `key=${this.apiKey}`,
      `part=snippet`,
      `type=video`,
      `maxResults=10`,
    ].join("&");
    const queryUrl = `${this.apiUrl}?${params}`;
    return this.http.get(queryUrl).subscribe(data => {
      data.map(item => {
        return new SearchResult({
          id: item.id.videoId,
          title: item.snippet.title,
          description: item.snippet.description,
          thumbnailUrl: item.snippet.thumbnails.high.url,
        });
      });
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

错误:

ERROR in src/app/services/youtube-search.service.ts(26,5): error TS2322: Type 'Subscription' is not assignable to type 'Observable<SearchResult[]>'.
  Property '_isScalar' is missing in type 'Subscription'.
src/app/services/youtube-search.service.ts(27,12): error TS2339: Property 'map' doesnot exist on type 'Object'.
Run Code Online (Sandbox Code Playgroud)

Ven*_*omy 12

你的search方法正在返回a subscription但是签名声称它应该返回一个Observable<SearchResult[]>

要解决此问题,请更改方法的签名或更改subscribemap

  • `import'rxjs/add/operator/map'` (2认同)