Utilizing the angularJS API to retrieve data

I am completely new to AngularJS and feeling overwhelmed.

So I created this file to fetch data from an API with a time filter.

forecast.js

(function() {

angular.module('application').factory('Forecast', ['$http', '$q', function($http, $q){

  var ApiAddr = "api.com/";


  forecast.getResults = function(timeStart, timeEnd){
    // Mapping application variable names with API parameter names
    var httpParams = {
      type: "global",
      time: "minute",
      tsmin: timeStart,
      tsmax: timeEnd
    };
    return $http.get(apiAddr, {
      params: httpParams,
      cache: true
    }).then(function(data){
      return data;
    },
            function(response){
              console.log(
          "HTTP request "+ApiAddr+
          " (with parameters tsmin="+httpParams.tsmin+", tsmax="+httpParams.tsmax+
          ", type="+httpParams.type+", time="+httpParams.time+
          (httpParams.motive ? ", motive="+httpParams.motive : "")+
          (httpParams.vector ? ", vector="+httpParams.vector : "")+
          (httpParams.media ? ", media="+httpParams.media : "")+
          ") failed with "+response.status
        );
        return $q.reject(response);
      }
    );
}];

But I have no clue how to create a controller adapter for this. What type of controller should I use? All the examples I've found are based on fixed JSON files with no parameters.

Additionally, I want to input the time filter in HTML, but I have no idea where to start. The examples I've seen only show how to retrieve data, not send it.

Ps: I have spent 2 days researching this, as I have never worked with front-end programming before.

Answer №1

(function() {

  angular.module('weatherApp', [])
    .factory('WeatherForecast', ['$http', '$q', function($http, $q) {
      var apiAddress = 'api.weather.com';
      var weatherForecastData = {};

      weatherForecastData.getResults = function(startTime, endTime) {
        // Mapping application variables with API parameter names
        var httpParameters = {
          type: "global",
          time: "minute",
          tsmin: startTime,
          tsmax: endTime
        };
        return $http.get(apiAddress, {
          params: httpParameters,
          cache: true
        }).then(function(response) {
          return response.data;
        });
      };

      return weatherForecastData;

    }])
    .controller('MainController', ['$scope', 'WeatherForecast', function($scope, WeatherForecast) {
      $scope.forecastReport = '';

      $scope.getWeatherForecast = function() {
        WeatherForecast.getResults($scope.startTime, $scope.endTime)
          .then(function(report) {
            $scope.result = report;
          }).catch(function(error) {
            $scope.result = '';
            console.error('Failed to retrieve forecast report: ' + error);
          });
      };
    }]);

})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="weatherApp" ng-controller="MainController">
  <label>Start Time:
  <input type="text" ng-model="startTime"/></label>
    <label>End Time:
  <input type="text" ng-model="endTime"/></label>
  
  <button ng-click="getWeatherForecast()">Get Weather Forecast</button>
  <hr/>
  <div>
  <b>Weather Forecast:</b>
  </div>
  <pre>{{forecastReport | json}}</pre>
</div>

Answer №2

To incorporate the factory into your controller, follow these steps:

var app = angular.module('app');
app.controller('myController',
      ['$scope', 'Forecast', function($scope, Forecast) { /* access to Forecast */ }]);

Alternatively, you can use a component for a cleaner approach:

app.component('myComponentCtrl', {
       templateUrl: 'template.html',
       controller: myComponentCtrl
})

myComponentCtrl.$inject = ['$scope', 'Forecast'];

function myComponentCtrl($scope, Forecast) {/* ... */}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can Express.Multer.File be inserted into a FormData object easily?

Can anyone assist me in figuring out how to add a file of type Express.Multer.File into a FormData object? Situation: I have received a file with the type Express.Multer.File (I am using nestjs and followed this part of the documentation: https://docs.nes ...

Achieving successful functionality with position:relative in IE9

Having difficulty with the position: relative property in IE9. Check out this demo for reference: <div style="overflow:scroll;height:120px;"> <table id="table" width="100%"> <tr style="position:relative;background-color:#1b72a4;"> ...

Issue with Node.js connection to MySQL database resulting in timeout error (ETIMEDOUT)

I am attempting to establish a basic connection to an online mysql database using a node.js server. Here is the code I have written for this purpose: var mysql = require('mysql'); var con = mysql.createConnection({ host: 'example.org& ...

Javascript Prompt Cancel Button fails to function as intended

One issue I have encountered is that when using a prompt window for user input, if the user clicks Cancel, it returns null and the code continues to execute. However, I want the Cancel button to actually cancel the operation. I've attempted different ...

Tips for keeping the current tab active when a link opens a new tab using Javascript

There are many posts on this, but none seem to have a solution.I think it can be done. If you have a link with target='_blank', the page will open in a new tab, and it will be in focus. However, if you press the CTRL key when you click that lin ...

The initial axios GET request fails to retrieve data upon the first click

Having trouble retrieving data with button click. The issue is that the data is not fetched when clicking the button for the first time, but works fine on the second click. Here's the code snippet: const learnMores = document.querySelectorAll('. ...

Employing passport-steam alongside sails-generate-auth

As I develop my SailsJS application, I am aiming for users to authenticate solely through Steam. I utilized `sails-generate-auth` to set up some boilerplate code with sails routes, but integrating passport-steam has proven challenging. If you are interest ...

Issue with Pop Up not redirecting correctly after a successful login in Azure AD

I recently integrated Azure AD with my web application. When clicking on the login window, a pop-up appears with the URL . It prompts for the Azure AD username and password. However, after successfully logging in, a code is returned as a parameter but the ...

Using a string as a key for an object's property

function createObject(argName, argProperties){ var object = {}; object[argName] = argProperties; } I am calling my function in the following manner. createObject('name', objectProperties); The issue I am encountering is w ...

Generate Bootstrap 5 Navbar <li> and <ul dropdown item> dynamically using JavaScript

Requesting assistance I have stored text in the constant.js file as shown below. export const navLinks = [ { id: "manage", title: "Manage", }, { id: "transactions", title: "Tran ...

Discovering which particular check in the Express Validator is causing the errors can be done by following these steps

I am currently developing a web application that requires an admin user to create new users. The admin user's username and password are stored in the .env file, and I am utilizing the dotenv package for this purpose. However, I am facing an issue when ...

send array to the sort function

How can I sort a data array that is returned from a function, rather than using a predefined const like in the example below: const DEFAULT_COMPETITORS = [ 'Seamless/Grubhub', 'test']; DEFAULT_COMPETITORS.sort(function (a, b) { re ...

Toastr - encountering a problem with the settings

After invoking a toastr message using the following command: Command: toastr["success"]("foo") toastr.options = { "closeButton": false, "debug": false, "newestOnTop": false, "progressBar": false, "positionClass": "toast-bottom-right", "prev ...

Filtering an array in Node.js using multiple terms

I am currently working with a files array that includes various text files organized in a specific format: [test/fixtureData/fixtureData2/test3.inc, test/fixtureData/fixtureData3/test5.inc, test/fixtureData/test1.inc, ,test/fixtureData/test6.ssi ,test/fix ...

Identifying issues in jQuery code - What could be causing this error?

My jQuery code is not responding at all, not even showing an error! I'm not sure why, but here is the jQuery Code I'm using: /* This part is working fine */ $(".add-blog .blog-add-form .add-article .input-group select").on("change", function() ...

AngularJS failing to load controller for my specific scenario

Whenever I try to load my controller, I keep getting an error. I have double-checked all my files, but I can't seem to figure out where the mistake lies. Can anyone help me with this? This is my html file: <!DOCTYPE html> <html ng-app="tcp ...

Creating a dynamic checkbox feature in Angular using iterations

I'm currently working on a loop that generates checkboxes from a collection. Everything works fine so far, but now I need to set a limit of 8 checkboxes that can be checked (while still displaying all checkboxes). I attempted to use ng-model (and als ...

Is it feasible to completely erase the coding history of a website that has been indexed

Is it possible to completely erase the code-history of a website once it has been indexed by Google and other search engines? I have some content on a website that I want to remove from history, but I'm not sure if it's possible due to factors li ...

Tips for storing a GET response in a variable using ExpressJS and LocomotiveJS

I am currently navigating the world of NodeJS and have successfully developed an app using ExpressJS and LocomotiveJS framework. I am now faced with a challenge: how do I store a particular GET response in a variable within a controller? For instance: fil ...

Checking the status of an Xmlhttp request when the URL is inaccessible, all without the use of libraries

I am currently working on testing the functionality of a given URL using Ajax. In order to achieve this, I made some modifications to the Ajax code. function checkURLStatus() { var xmlhttp; if (window.XMLHttpRequest) { // code for IE7+, Firefox, Ch ...