I've developed a service that successfully makes an API request:
@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(touringArtists => touringArtists
.map(artist => new TouringArtist(
artist.field_touring_artist_name[0].value,
artist.field_touring_artist_id[0].value
))
)
.catch(this.handleError);
}
}
However, there is an issue where a new request is made every time a user navigates to the page and back. In my previous experience with React-Redux, I would maintain state, check it, and only trigger the API call when necessary. When attempting to implement this approach in Angular using TypeScript, I encountered a type error.
@Injectable()
export class TourService {
private touringUrl: string = `http://localhost/error-records/api/tour`;
private touringArtists: 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(touringArtists => {
const artists = touringArtists.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);
}
}
When trying the above implementation, an error is triggered:
Type 'TouringArtist[]' is not assignable to type 'Observable<any>'. Property '_isScalar' is missing in type 'TouringArtist[]'.