无法将类型"Subscription"分配给类型"Observable< SearchResult []>"使用HttpClient而不是Http的Angular 5 [英] Type 'Subscription' is not assignable to type 'Observable<SearchResult[]>' Angular 5 using HttpClient instead of Http

查看:97
本文介绍了无法将类型"Subscription"分配给类型"Observable< SearchResult []>"使用HttpClient而不是Http的Angular 5的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to use the new HttpClient class instead of the old Http.

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

I want to map over the data I get from the subscribe method, but get the below error. Any suggestions on why I get this?

代码:

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,
        });
      });
    });
  }
}

错误:

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'.

推荐答案

您的search方法返回subscription,但签名声称它应返回Observable<SearchResult[]>

Your search method is returning a subscription but the signature claims it should return an Observable<SearchResult[]>

要解决此问题,请更改方法的签名或将subscribe更改为map

To fix this either change the signature of your method or change the subscribe to map

这篇关于无法将类型"Subscription"分配给类型"Observable&lt; SearchResult []&gt;"使用HttpClient而不是Http的Angular 5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆