ItFreak
ItFreak

Reputation: 2369

Angular 6 http service best practice

i have a feed service in angular that calls a REST endpoint which returns a List of EntryDTO. Here is how the service looks like:

@Injectable({providedIn: 'root'})

constructor(private http: HttpClient) {}
export class FeedService() {
  getPublicFeedEntries: Observable<EntryDTO[]> () {
    return this.http.get('/rest/publicFeedEntries/).map((response: Response) => response.json()).catch((err: any) => Observable.throw(error.josn().error || 'error');
  }
}

So then i could have a feed component that subscribes to this observable:

export class FeedComponent() {
private feedEntries: EntryDTO[];
constructor(private feedService: FeedService) { feedEntries = new Array(); }

ngOnInit() {
  this.feedService.getPublicFeedEntries.subscribe(entries => {
  this.feedEntries = entries;
  }, err => {console.log(err) })
 }
}

Is this considered as best practice to return the observable in the service and subscribe in the component or are there other best practices?

Upvotes: 7

Views: 3250

Answers (1)

Kedar9444
Kedar9444

Reputation: 1853

The approach you are following is perfectly fine but to take it to new level you can introduce model's in your service which will make the response easy to read/use in your components.

Check this article written on ngx-model which provides way to follow a models driven approach in your application.

Upvotes: 1

Related Questions