【问题标题】:Angular - How to make a get request to an api to retrieve products?Angular - 如何向 api 发出获取请求以检索产品?
【发布时间】:2017-03-13 14:21:37
【问题描述】:

我想显示产品,需要通过连接到 api(使用令牌)来发出获取请求,以便使用 angular 获取产品(显示)。我真的不知道 如何做到这一点,尝试像在 Angular 的文档中那样做,但它不起作用。任何帮助,将不胜感激。谢谢! 角度:

var app = angular.module('myApp', []);
app.controller('myAppCtrl', function($scope, $http) {

        $http({
        method: 'GET',
        url: 'http://testing.com/page/go',
        config: {
            params: {
                token: "1234x.1234x",
            }
        }
    })
    .then(function(products) {
        products.data;
    })
    .then(function(allProducts) {
        $scope.products = allProducts;
    })
});

html:

<body ng-app="myApp" ng-controller="myAppCtrl">
    <div>
        <ul>
            <li ng-repeat="product in products"> {{product}} </li>
        </ul>
    </div>
</body>

【问题讨论】:

  • "products.data;" 什么都不做。您可能需要添加一个 return 语句。
  • 如果我返回 products.data,什么也不会发生

标签: angularjs api get


【解决方案1】:

我不明白为什么你有两个thens,而且你没有将 products.data 存储在任何地方,所以你可以使用它们。试试这个代码:

var app = angular.module('myApp', []);
app.controller('myAppCtrl', function($scope, $http) {

    $http({
        method: 'GET',
        url: 'http://testing.com/page/go',
        config: {
            params: {
                token: "1234x.1234x",
            }
        }
    })
    .then(function(products) {
        $scope.products = products.data;
    })
});

如果您检查 angular http 文档,永远不会有 2 个thens,而是一个有 2 个参数,第一个表示成功,第二个表示失败。

$http(req).then(function(resp){...}, function(err){...});

【讨论】:

  • 谢谢。那时我有 2 个,因为我有点认为我必须先返回数据,然后将其分配给 $scope.products ..但我想我不必这样做。我试过你的代码,它也不起作用。当我连接到请求数据的 api 时,除了 http get 请求,我还需要做什么吗?我收到此错误:可能未处理的拒绝:{"data":{"status":"error","message":"Token missing","errorNo":1000}
猜你喜欢
  • 2014-04-03
  • 2018-03-03
  • 1970-01-01
  • 2014-06-29
  • 2018-06-26
  • 2021-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多