Swap - HttpClient
Fetching data, Observables and Subscription
Context
With Angular we have the HTTPClient . This returns an Observable, that we subscribe to and do all sorts of cool things. Well, the thing to understand is that this is not something unique to Angular, but is actually the handiwork of a library - RxJs
With Angular, we are used to creating Services. Inject dependencies into services, which then are used to abstract methods and other utilities. and with StencilJS, there are no services, just Components.
Alternatives
Create a .ts file - data.service.ts - which exports a function, that makes the API call.
RxJS fromFetch - https://rxjs-dev.firebaseapp.com/api/fetch/fromFetch ( Uses the Fetch API to make an HTTP request.) , but returns an Observable.
Flow
The component calls the fetchEvents ( a method ) from within the Service Component, which makes the API call - and returns an Observable.
The component subscribes to this, and as data comes in, it changes the state - and if necessary, that would get passed to the child component via Props.
Observables would be subscribed in the componentWillLoad() lifecycle hook. ( since it's called only once ), and unsubscribed in the disconnectedCallback().
Last updated
Was this helpful?