【问题标题】:$http.get in Angular doesn't workAngular 中的 $http.get 不起作用
【发布时间】:2016-11-11 18:54:25
【问题描述】:

当我尝试从我的数据库 (mongoDB) 获取数据时,$http.get 出现问题。

我正在使用平均堆栈。

angular.module('wildroseApp')
.controller('WildroseComponent', function($scope, $http){
    $http.get('/api/wildrose')
        .success(function (data) {
        $scope.wildrose = data;
        console.log($scope.wildrose);
    })
        .error(function (err) {
        alert('Error!');
    });
})
.component('wildrose', {
    templateUrl: 'app/wildrose/wildrose.html',
    controller: WildroseComponent,
    controllerAs: Wildrose
});

另外,我还有一个问题:

当我在组件中使用controllerAs 时,我的浏览器显示

未捕获的 ReferenceError: Wildrose 未定义

但是,如果删除它就可以了。

我尝试如下解决:

只需在构造函数中添加一点代码:

class WildroseComponent {
  constructor($http) {
    this.$http = $http;
    this.wildrose = [];
  }
  $onInit(){
      this.$http.get('/api/wildrose')
          .then(response => {
              this.wildrose = response.data;
              console.log(this.wildrose);
          });;
    }
}

【问题讨论】:

  • 你使用的是哪个版本的 AngularJs?
  • 您的问题/问题是什么? “不起作用”到底是什么意思?
  • 当我使用 $http.get 从我的数据库中获取数据时,console.log($scope.wildrose) 中没有任何显示,但这里应该是 json 字符串
  • 请尝试将您的 AngularJs 更新到 1.5.7,HTH ;)。

标签: angularjs node.js mongodb express yeoman


【解决方案1】:

ControllerAs 需要字符串而不是对象:

controllerAs: "wildrose"

您是否在服务器上使用/api/wildrose 下的 node/express 设置了一个端点,该端点返回从您的数据库读取的 json 字符串?

请提供更多后端代码和错误,否则很难诊断。

【讨论】:

  • 是的,我使用 yeoman 生成器创建了端点,这是来自控制器的代码 // 获取 Wildroses 导出函数的列表 index(req, res) { return Wildrose.find().exec() .then(respondWithResult (res)) .catch(handleError(res));这是 index.js router.get('/', controller.index);当我使用 $http.get 时没有错误只是没有显示
  • 如果你使用chrome,开发工具下的网络面板是什么意思?请求发送正确?后端的响应是什么?
  • 有一件事,我不确定 MEAN,但是 mongodb 的 find 方法需要一个对象作为参数。如果要查找集合的所有条目,请使用空对象 .find({})
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-09
  • 2014-10-03
  • 1970-01-01
  • 2018-01-18
  • 2017-12-16
相关资源
最近更新 更多