Angular – Observables

On the last article, we discussed what a Template Reference Variable is. In this article, we will talk about Observables.

Stack Overflow defines observables as a class that maintains a list of observers. When an Observable object is updated, it invokes the update() method of each of its Observers to notify that, it is changed.

To use the observables library to fetch data from a web service, we are going to follow these steps:

1. Import the necessary HTTP Resources

In your IDE, open the stock.service.ts. The necessary resources should be imported there.

observables

  • Here, we basically created a dependency injection of ‘http’ in the constructor method for our StockService class.

2. Create an Observable method

This method is used to fetch data from the web service. In the same file, we’re going to add the method.

observables

  • A getStocksAPI:Observable method is added to get <any> type of object.
  • Data is returned from the URL of our JSON web service.
  • .map controls the response for a specific data.
  • .catch handles any error management in the request.

Save your work and now let’s go to dashboard.component.ts file for the 3rd step.

3. Add the Service we created to the Dashboard Component

This time, we are going to use the dashboard.component.ts. Open it and import our Stock Service.

observables

If you notice, we used double period for our source of import. It is because the file is one folder up from our dashboard.component.ts file.

observables

Then inject our StockService component to the constructor.  

observables

4. Add a Subscriber method

Then below the constructor created above, add the method.

observables

  • It’s called a Subscriber method because of ‘.subscribe’ command.
  • Basically, this method fetches data from stocks API and returns an error whenever such event occurred.

5. Invoke the Subscriber method on the ngOnInit() method

Just insert the method inside the ngOnInit section and after this last step, dashboard.component.ts should look like this.

observables

From here, our application is now ready to be tested. In your integrated terminal type the command ng serve. Go back to your browser at localhost:4200.

observables

And that is how observables work. On the next section, we will thoroughly discuss HTTP.

Subscribe Now and Upgrade Your Skills Today!
Sign up now and have the latest tech tutorials delivered straight to your mailbox.

PLUS: Get exclusive member-only discounts (up to 80% OFF!!) on our top tech courses in Udemy!
We hate spam. Your email address will not be sold or shared with anyone else.