我如何从后端Express JS项目获取数据以在带有角度JS的前端html视图中显示它

问题描述 投票:0回答:1

我来自PHP背景,并且是Node和Angular的新手。我有一个后端项目,我创建了一个API路由来显示模块中的一些数据。数据运行良好,并显示在邮递员中。我正在尝试在Angular JS项目中显示它。它具有一个模块和一个控制器JS文件以及一个html视图。该视图很好地显示了该JS文件中的硬代码数据,但我想从API中获取数据。我搜索并找到此语法

var courseApp = angular.module('courseApp', ['ui.bootstrap', 'seeMoreFilter', 'ngSanitize']);


courseApp.controller('courseCtrl', ['$scope', '$http', 'filterFilter', function ($scope, $http, filterFilter) {

    $http.get("api/courses/").success(function (data) {
        $scope.courses = data;
        alert( "Load was performed. " + data );
    });

}]);

我也发现了这一点,但不幸的是它们都不起作用

$http({
    method: 'GET',
    url: 'api/courses'
}).then(function (response) {
    console.log(response);
    $scope.courses = response.Course;
}, function (error) {});

有更好的方法还是有什么麻烦?

node.js angularjs express mean-stack
1个回答
0
投票

更改此:

 $http.get("api/courses/").success(function (data) {
        $scope.courses = data;
        alert( "Load was performed. " + data );
    });

为此:

 $http.get("api/courses/").success(function ({data}) {
        $scope.courses = data;
        alert( "Load was performed. " + data );
    });

您得到的是一个响应对象。实际的响应主体位于属性“数据”下。

来自文档:

The response object has these properties:

data – {string|Object} – The response body transformed with the transform functions.
status – {number} – HTTP status code of the response.
headers – {function([headerName])} – Header getter function.
config – {Object} – The configuration object that was used to generate the request.
statusText – {string} – HTTP status text of the response.
xhrStatus – {string} – Status of the XMLHttpRequest (complete, error, timeout or abort).
© www.soinside.com 2019 - 2024. All rights reserved.