Single Angular Controller w/ multiple $HTTP Get request

1.1k Views Asked by At

I have two mongoose schemas running in on my server end. I would like to add two $http.get request in my app.js and eventually display two tables from my collection in MongoDB on a webpage. Only one get function is called without errors.

server.js

//Data Schema
var tempSchema = new mongoose.Schema({
    topic: String,
    message: Number,
    when: Date
}, {collection: "temperature"});

var humiditySchema = new mongoose.Schema({
    topic: String,
    message: Number,
    when: Date
}, {collection: "humidity"});

var temperature =mongoose.model('temperature', tempSchema);
var humidity =mongoose.model('humidity', humiditySchema);

app.js

app.controller("FormController", function ($http, $scope){
    $http.get("/api/temperature")
        .then(function (response) {
            $scope.temperatures = response.data;
        });
})

app.controller("FormController", function ($http, $scope){
    $http.get("/api/humidity")
        .then(function (response) {
            $scope.humiditys = response.data;
        });
})

Also thinking of how I can display both collections on the webpage. Using ng-repeat. Unfortunately I cannot paste my HTML code here.

I would appreciate any help I can get. Thanks

1

There are 1 best solutions below

13
On BEST ANSWER

Another way you could handle the $http requests is by creating an Angular Factory.

angular.module('myApp.services',[])

add.factory('ApiService', function($http) {
    return {
        getHumidity: function() {
            return $http.get("/api/humidity");
        },
        getTemperature: function() {
            return $http.get("/api/temperature");
        }
    }
})

Then inside your controller, you should do the following (Note that you must inject the factory as a dependency for the controller)

angular.module('myApp.controllers',[])
    .controller("FormController", function (ApiService, $scope){
         function getHumidity() {
            var promise = ApiService.getHumidity();
            promise.then(
                function(response) {
                    $scope.humiditys = response.data;
                },
                function(errorPayload) {
                    console.log(errorPayload);
                });
        };

        function getTemperature() {
            var promise = ApiService.getTemperature();
            promise.then(
                function(response) {
                     $scope.temperatures = response.data;
                },
                function(errorPayload) {
                    console.log(errorPayload);
                });
        };

        getHumidity();
        getTemperature();

    })

then where you define your angular App (app.js in most of the cases):

angular.module('myApp', ['myApp.controllers','myApp.services'])
    .run(...)
    .config(...)
    ...