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[]'.
return Observable.of(this.touringArtists);