代码之家  ›  专栏  ›  技术社区  ›  Salman

AngularJS将API请求从PHP更改为JSON

  •  0
  • Salman  · 技术社区  · 6 年前

    嗨,我有一个可以连接到API的应用程序。

    唯一的问题是它只能 get 来自的API请求 PHP 文件。

    我想更改代码以便它接受 .json API文件

    工厂

    factory.readProducts = function(){
        return $http({
            method: 'GET',
            url: 'https://jsonplaceholder.typicode.com/todos'
        });
        console.log(factory.readProducts)
    
    };
    

    目前我的 GET 方法应该更改为 fetch

    控制器

    $scope.readProducts = function(){
    
        // use products factory
        productsFactory.readProducts().then(function successCallback(response){
            $scope.todos = response.data.records;
             console.log($scope.products)
        }, function errorCallback(response){
            $scope.showToast("Unable to read record.");
        });
    
    }
    

    JSON方法

        fetch('https://jsonplaceholder.typicode.com/todos/1')
      .then(response => response.json())
      .then(json => console.log(json))
    

    根据 JSONPlaceholder 这是访问JSON API的基本方法

    1 回复  |  直到 6 年前
        1
  •  0
  •   Salman    6 年前

    需要从以下位置更改控制器:

    $scope.readProducts = function(){
    
        // use products factory
        productsFactory.readProducts().then(function successCallback(response){
            $scope.todos = response.data.records;
             console.log($scope.products)
        }, function errorCallback(response){
            $scope.showToast("Unable to read record.");
        });
    
    }
    

    收件人:

    $scope.readProducts=函数()。{
    
    //使用产品工厂
    productsFactory.readProducts()。然后(函数成功回调(响应){
    $scope.todos=response.data.records;
    console.log($scope.products)
    },函数错误回调(响应){
    $scope.showtoas(“无法读取记录”);
    (});
    
    }
    

    这个 $scope.todos = response.data.records 需要更改为 $scope.todos = response.data 因为API的结构。它与文件无关 JSON PHP

    推荐文章