-1

I am asking this question for learning purposes. Here is my service:

export class HomeService {
   private generalstatistics = new ReplaySubject<object>();
   constructor(
   private http: HttpClient
     ) {
    this.data();
  }
  public get generalStatistics(): Observable<object> {
    return this.generalstatistics.asObservable();
  }
  data() {
    this.http.get<any>(`${environment.apiUrl}/home/`)
    subscribe(data => {
    this.generalstatistics.next(data);
  });
 }
}

Here I have my first subscription. Then somewhere in a component that needs that data I have the following:

constructor(private dataSvc: HomeService) {
  this.getData();
}
getData() {
   this.dataSvc.generalStatistics
   .subscribe(data => {
   this.source = data;
 });
}

Which has my second subscription. So just for the learning purpose, is it possible to avoid two subscriptions?

Thanks

Mark
  • 4,535
  • 7
  • 39
  • 76

1 Answers1

1

You should instead of doing a subscription inside the service do this inside the component.

Eg.:

data() {
    return this.http.get<any>(`${environment.apiUrl}/home/`)
});

and accordingly do your subscription of this wherever you need it!

Inside a component e.g.:

this.homeservice.data().subscribe(...)

if you do this you will reduce complexity and have less code duplicates.

Hope it helps!

Kennuel
  • 169
  • 7
  • VS code says Property 'subscribe' does not exist on type '() => Observable' – Mark Dec 22 '19 at 16:01
  • I guess you need to cast it properly, have a look here: https://stackoverflow.com/questions/49627239/casting-a-type-interface-via-map-to-observable :) `getRestaurant() { this.restaurantProvider.getRestaurant().subscribe((res: restaurant) => { this.restaurant = res; }); }` Adding the type should resolve your issue - and will make your app more typesafe – Kennuel Dec 22 '19 at 16:04
  • I am changing my service to be like this: data(): Observable { return this.http.get(`${environment.apiUrl}/home/`) .map((response: any) => response.data as any); Error: Property 'map' does not exist on type 'Observable' – Mark Dec 22 '19 at 16:12
  • 1
    You need to `pipe` the `map` operator. You can't just stick them on the end since RxJS 6 – Will Alexander Dec 22 '19 at 16:56