使用Angular 4 Observables键入最小化API请求的错误

时间:2017-11-03 15:58:31

标签: angular typescript rxjs observable

我有一项服务可以使API请求正常工作:

@Injectable()
export class TourService {
  private touringUrl: string = `http://localhost/error-records/api/tour`;

  constructor(private http: Http) {}

  getTouringBands(): Observable<any> {
    return this.http.get(this.touringUrl)
    .map((res: Response) => res.json())
    .map(touringArists => touringArists
      .map(artist => new TouringArtist(
        artist.field_touring_artist_name[0].value,
        artist.field_touring_artist_id[0].value
      ))
    )
    .catch(this.handleError);
  }
}

但问题是,每次用户导航到页面并返回时,都会发出新请求。我来自React-Redux,我通常会把它保持在状态,检查状态,然后只在必要时才进行API调用。但是,当我尝试类似的东西时,我会遇到类型错误。

@Injectable()
export class TourService {
  private touringUrl: string = `http://localhost/error-records/api/tour`;
  private touringArists: TouringArtist[];

  constructor(private http: Http) {}

  getTouringBands(): Observable<any> {
    if (this.touringArtists) {
      return this.touringArtists;
    }
    return this.http.get(this.touringUrl)
    .map((res: Response) => res.json())
    .map(touringArists => {
      const artists = touringArists.map(artist => new TouringArtist(
        artist.field_touring_artist_name[0].value,
        artist.field_touring_artist_id[0].value
      ))
      this.touringArtists = artists;
      return artists;
    })
    .catch(this.handleError);
  }
}

如果我尝试上面的代码,我会收到错误Type 'TouringArtist[]' is not assignable to type 'Observable<any>'. Property '_isScalar' is missing in type 'TouringArtist[]'.

1 个答案:

答案 0 :(得分:1)

问题在于:

 getTouringBands(): Observable<any> {
    if (this.touringArtists) {
      return this.touringArtists;
    }

在第一行中,您说该函数的返回值为Observable<any>if条件中,您返回touringArtists,即ouringArtist[]

您可以将其作为可观察对象返回:

 getTouringBands(): Observable<any> {
    if (this.touringArtists) {
      return Observable.of(this.touringArtists);
    }