如何检查返回的对象是否为空或在AngularJS中填充

时间:2015-01-16 15:29:56

标签: javascript c# angularjs

我正在开发Sample Quiz应用程序。所以我在C#中使用Web Api的代码会调用数据库并获得一个与传递的id匹配的测验。数据以JSON格式返回。

如果找到与id匹配的测验,则这是传递的数据:

{"Id":2,"Options":[{"id":1,"qid":2,"option":"50 mi/hr","result":false},{"id":2,"qid":2,"option":"756 mi/hr","result":false},{"id":3,"qid":2,"option":"765 mi/hr","result":true},{"id":4,"qid":2,"option":"630 mi/hr","result":false}],"Question":"What is the speed of sound through air "}

Quiz: id, Options[],Question.

如果未找到测验,则返回空输出:

{"Id":0,"Options":[],"Question":null}

现在在AngularJS中,我试图检查返回的内容是否等于空输出。这是我写的代码,但它不起作用:

SimpleQuiz.factory('Quiz', function ($resource) {
    return $resource('/api/Quiz/:id', { id: '@id' }, { update: { method: 'PUT' } 
});

$scope.startQuiz = function ()
{
    // and id is passed into the Quiz.get function
    // and the returned output is stored in $scope.item
    $scope.item = Quiz.get({ id: $scope.quizid });

    var sampleitem = $scope.item

    // this is the part that isn't working
    if (angular.equals(smpleitem,emptyQuizObject))
    {
        // redirect if they are the same
        $location.path('/start');
    }
    else
    {
        // output to the screen
        $scope.item = $scope.item; // this works
    }
}// end start quiz

var emptyQuizObject = {"Id": 0, "Options": [], "Question": null };
$scope.startQuiz(); // start the quiz

Web Api的C#代码:

public class QuizController : ApiController
{
    public QuizQuestion Get(int id)
    {
        QuizQuestion question = Models.DbStoredProcModel.GetQuiz.GetaQuiz(id);
        return question;
    }
}

0 个答案:

没有答案