1

I have a service that makes an API request that works fine:

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

but the problem is, every time a user navigates to the page and back, a new request is made. I'm coming from React-Redux, where I would generally hold it in state, check the state, and then only make the API call if necessary. However, when I try something like that, I get a type error.

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

If I try the above code, I get the error Type 'TouringArtist[]' is not assignable to type 'Observable<any>'. Property '_isScalar' is missing in type 'TouringArtist[]'.

2
  • 2
    On the second line of your function you are returning an array but Typescript expects an Observable<any> because you told it that that is the return type for the function. You can return an observable by changing line #2 to: return Observable.of(this.touringArtists); Commented Nov 3, 2017 at 16:00
  • Thanks @bygrace! That worked. Commented Nov 3, 2017 at 16:08

1 Answer 1

1

The problem is here:

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

In the first line, you say that the return of the function is Observable<any>.
Inside the if condition you return touringArtists, which is ouringArtist[].

You can return it as an observable like:

 getTouringBands(): Observable<any> {
    if (this.touringArtists) {
      return Observable.of(this.touringArtists);
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.