简体   繁体   中英

http get and post Angular

Hello here's my json "names" :

[
    {
        "file": "file1.zip",
        "date": "12-03-2016",
    },
    {
        "file": "file2.zip",
        "date": "24-06-2016",
    },
    {
        "file": "file3.zip",
        "date": "02-12-2016",
    }]

My javascript file:

var app = angular.module('app', []);
    app.service('service', function($http, $q){
        var deferred = $q.defer();

        $http.get('newapi.json').then(function(data){
            deferred.resolve(data);
        });

        this.getNames = function(){
            return deferred.promise;
        }
    });
    app.controller('FirstCtrl', function($scope, service){
        var promise = service.getNames();
        promise.then(function(data){
            $scope.names = data.data;
            $scope.namesplit = $scope.names;
            $scope.namesplit.map(function(item) {
                item.time = new Date(item.date * 1000);
            });
            console.log($scope.namesplit);
        });
        });

and HTML :

<tr ng-repeat="name in names">
   <td>{{name.file}}</td>
   <td>{{name.date}}</td>
   <td><button>POST</button></td>
</tr>

Well i have a table and what i need is when i click on button, the "file" post to serwer. I know i must use $http.post but i don't know how to do it.

So Simple Html

<button ng-click="post()">Click Me</button>

Controller

    $scope.post=function(){
$http.post(URL HERE, data-here, {    
 })
  .then(function onSuccess(response) {
    // Handle success
    var data = response.data;
    var status = response.status;
    var statusText = response.statusText;
    var headers = response.headers;
    var config = response.config;
    ...
  }).
  catch(function onError(response) {
    // Handle error
    var data = response.data;
    var status = response.status;
    var statusText = response.statusText;
    var headers = response.headers;
    var config = response.config;
    ...
  });
  }

For upload a file using $http.post() function you have to set some additional parameters like headers and and transformRequest .

Here a simple example:

$scope.postToServer = function(){
    var fd = new FormData();
    fd.append('file', file); 
    $http.post(uploadUrl, fd, {
        transformRequest: angular.identity,
        headers: {'Content-Type': undefined}
    })
    .success(function(){
    })
    .error(function(){
    });
}

Note: in this example the file var is the content of the file located on client file system and the uploadUrl is the URL of your service that handle the request.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM