Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 252
ItFreak Avatar asked Aug 16 '18 07:08

ItFreak


1 Answers

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.

like image 163
Kedar9444 Avatar answered Nov 15 '22 07:11

Kedar9444