7

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?

8
  • Yes, normally the services return observables and in the component we subscribe to this observables. NOTE: If you use httpClient NOT use map(res=>res.json(). You need't do it Commented Aug 16, 2018 at 7:59
  • How do i get the json representation then? otherwise i cant assign the response to my array, right? Commented Aug 16, 2018 at 8:00
  • HttpClient, by defect, give you the json object directly. (use a console.log(res) to check it) Commented Aug 16, 2018 at 8:02
  • 2
    You should also consider using .pipe(takeUntil( /* Subject */)). I usually have a property destroyed$: Subject<void> = new Subject<void>(); and call this.destroyed$.next() in the ngOnDestroy hook. This will stop the subscription once the component is destroyed and will stop any subscription leaking which might affect performance. Commented Aug 16, 2018 at 8:17
  • 1
    @ItFreak yea, you're doing it wrong. Here, you can read more about it in this article. Commented Aug 16, 2018 at 14:10

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.