Type 'Subscription' is not assignable to type 'Observable<SearchResult[]>' Angular 5 using HttpClient instead of Http

天涯浪子 提交于 2019-12-12 08:27:58

问题


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

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?

Code:

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:

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

回答1:


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

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




回答2:


To return the Observable, use:

return this.http.get(queryUrl);

and do the subscription on the calling end. If you need to map your return object from the Http call to a different object. Then one solution would be to define a subject and inside your subscription, you perform a next operation on this subject.

As for the second error, you are getting for using map function. You can use return this.http.get(queryUrl); to make the compiler view it as a an array instead of a single object. I am not sure that this what you wanted to achieve or not.




回答3:


easily , you don't use for return value.

.valueChanges()


来源:https://stackoverflow.com/questions/47220907/type-subscription-is-not-assignable-to-type-observablesearchresult-angul

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!