RSS feed in AngularJS

By | October 8, 2020

 

Introduction

This post provide details on how to read RSS feed in an AngularJS application.

Web Application

The AngularJs web application structure was initially generated using Yeoman scaffolding. It was modified to adhere some of the best practices. The structural changes brought modifications in grunt file for getting right dependencies and files generated when published.

This post will however not focus on structural changes. It will give snippets and dependencies that were used to read RSS feed and display it in an AngularJS application.

Code

Service

This service use google api to fetch feed as a JSON response.

(function() {
  'use strict';

  angular.module('demoApp.services')
    .service('FeedService', ['$rootScope', '$http',
      function($rootScope, $http) {

        /*-------------------------------------------------------------*/
        /* Get RSS live feed
        /*-------------------------------------------------------------*/
        function getRssFeed() {

          var googleApi = '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=100&callback=JSON_CALLBACK&q=';
          var requestUrl = "http://www.cnn.com/services/rss/";

          return $http.jsonp(googleApi + encodeURIComponent(requestUrl));
        }

        /*-------------------------------------------------------------*/
        /* Exposing service APIs
        /*-------------------------------------------------------------*/
        var feedService = {
          getRssFeed: getRssFeed
        };

        return feedService;
      }
    ]);
})();

Controller

The controller uses FeedService to read JSON response and pick the feed that needs to be displayed from each category. In this example we will try to display couple of categories. These categories will be read from feed JSON response and first object in each category will be provided as datasource to a News component.

(function () {
  'use strict';

  angular.module('demoApp.controllers')
    .controller('HomeController', ['$scope', '$rootScope', 'FeedService', 'FlashService',
      function($scope, $rootScope, FeedService, FlashService) {
        var currIndex = 0;

        /*-------------------------------------------------------------*/
        /* Groups feed array to their respective categories. This function will allow
        /* access to each category by regular javascript syntax.
        /*-------------------------------------------------------------*/
        var groupBy = function(xs, key) {
          return xs.reduce(function(rv, x) {
            (rv[x[key]] = rv[x[key]] || []).push(x);
            return rv;
          }, {});
        };

        /*-------------------------------------------------------------*/
        /* Initialize home, get feed information
        /*-------------------------------------------------------------*/
        $scope.initialize = function() {
            $scope.getRssFeed();
        };

        /*-------------------------------------------------------------*/
        /* Get RSS Feed
        /*-------------------------------------------------------------*/
        $scope.getRssFeed = function () {
          FeedService.getRssFeed()
            .then(function(response) {
              if (response && response.data && response.data.responseData && response.data.responseData.feed) {
                var groupedFeed = groupBy(response.data.responseData.feed.entries, 'categories');

                //The feed is already sorted on published date. no need to sort.
                if(groupedFeed) {

                  //Case studies
                  if(groupedFeed["Case Studies"] && groupedFeed["Case Studies"].length > 0) {
                    $scope.caseStudy = groupedFeed["Case Studies"][0];
                  }

                  //News
                  if(groupedFeed.News && groupedFeed.News.length > 0) {
                    $scope.news = groupedFeed.News[0];
                  }
                }
              } else {
                FlashService.showError("Failed to get feed.", false);
              }
            }, function() {
              FlashService.showError("Failed to get feed.", false);
            });
        };

        /*-------------------------------------------------------------*/
        /* Initialize called on load
        /*-------------------------------------------------------------*/
        $scope.initialize();

      }]);
})();

Each RSS category first item is set to a given scope variable (caseStudy and news). These scope variables can be displayed on a view.

I am sure there are new and better ways to achieve the same thing but I used this way around a year back on Angular 1.5.

Leave a Reply

Your email address will not be published. Required fields are marked *