Deepak
Deepak

Reputation: 376

Error Message doesn't show for factory Angular.js

I've a factory method in my Code as:-

    (function () {
    var app = angular.module('MyApp', []);  
    app.controller('MYController', function ($scope, CourseDescFactory) {  // here $scope is used for share data between view and controller
        $scope.MyDescCourses = [];
        CourseDescFactory.OurCourses().then(function (d) {
            $scope.MyDescCourses = d.data;
            $scope.MainHeading = $scope.MyDescCourses[0].CD.MainHeading;
            $scope.MainDesc = $scope.MyDescCourses[0].CD.MainDesc;
            $scope.MainImg = $scope.MyDescCourses[0].CD.Img;

            $scope.MySubDescCourses = [];
            $scope.MySubDescCourses = $scope.MyDescCourses[0].CSD;
            //$scope.Img = $scope.MyDescCourses[0].Img;
        }, function (error) {
            alert('Cannot Load Course Detail');
        });
    })
.factory('CourseDescFactory', function ($http) {
    var CourseDescList = {};
    CourseDescList.OurCourses = function (id) {
        return $http({
            method: 'GET',
            url: '/Home/CourseDesc',
            params: {}
        });
    }
    return CourseDescList;
});

})();

This works fine when I've data from backend . But when there is no data, instead of showing alert('Cannot Load Course Detail'); it throws an error 'Cannot read property 'CD' of undefined'.

Any help will be appreciated.

Upvotes: 0

Views: 34

Answers (1)

Ruchira Chamara
Ruchira Chamara

Reputation: 345

It is better to check your response variable which is "data" and it's inside content with the following commands.

     if (
         (d.data != undefined) && (d.data != null) && (d.data != "") 
        )

Upvotes: 1

Related Questions