logo
down
shadow

angular async upload file with promises


angular async upload file with promises

By : baddai
Date : November 19 2020, 01:01 AM
I wish this helpful for you I'm new to angular, and i'm little bit confused via doc's from official site... , Inject angular's deferred:
code :
.service('uploaderService', ['$http', '$q', 'settings', function ($http, $q, settings) {
var addImage = function(files){

    var deferred = $q.defer();

    var fd = new FormData();
    fd.append("file", files[0]);
    $http.post(settings.apiBaseUri + "/files", fd, 
    {
        withCredentials: true,
        headers: {'Content-Type': undefined },
        transformRequest: angular.identity
    })
    .success(function (data, status, headers, config) {         
        url = "temp.jpg";
        deferred.resolve(data);
    })
    .error(function (err, status) {
        console.log('operation failed, status: ' + status);
        deferred.reject({msg: err});
    });

    return deferred.promise;
};
uploaderService.addImage(files)
    .then(function(data){
        // success
        var url = data.url; // assuming the returned data of the ajax call contains an url variable
    }, function(error){
        // error
    }).finally(function(){
        // always
    });


Share : facebook icon twitter icon
Promises issue with async and sync - angular

Promises issue with async and sync - angular


By : user224685
Date : March 29 2020, 07:55 AM
seems to work fine This is how I got it working. I tried using @JLRishe's suggestion but it wouldn't work. Turns out, I managed to pass more than one parameter through to the service method and back to the controller as well (by building an object than contains as many parameters I need).
code :
myService.getSomeData().then(
    function (stuff) {
        // whatever
    }
).then(function () {
    for (var i = 0; i < $scope.model.stuff.length; i++) {

        // HERE I SEND TWO PARAMETERS TO THE SERVICE METHOD
        myService.getSomeMoreData($scope.model.stuff[i].id, i).then(
            function (data) {
                // whatever
            }
        );
    }
});

this.getSomeMoreData = function (id, index) {
    var deferred = $q.defer();
    var query = "SELECT * FROM stuff";

    $cordovaSQLite.execute(db, query).then(function (res) {
        var moreStuff = [];

        for (var i = 0; i < res.rows.length; i++) {
            var junk = res.rows.item(i);
            moreStuff.push(junk);

        }

        // HERE I RESOLVE AN OBJECT INSTEAD OF TWO PARAMETERS
        deferred.resolve({
            moreStuff: moreStuff,
            index: index
        });

    }, function (err) {
        deferred.reject(err);
    });

    return deferred.promise;
};
Make multiple Async Request using Angular Js Promises

Make multiple Async Request using Angular Js Promises


By : Gustavez
Date : March 29 2020, 07:55 AM
I hope this helps . I have an array of cities with their name and url . , You can use recursive loop like in this example:
code :
var app=angular.module("app",[]);

app.controller("main",function($scope,$q,$http){

  
$scope.cities = [{'name':'LKO','url': 'http://stackoverflow.com/posts/39497624'},{'name':'LK1O','url': 'http://stackoverflow.com/posts/39497624'},
{'name':'LK21','url': 'http://stackoverflow.com/posts/39497624'}]
   
  //recursive function
  function getUrl(i){
      
      if (typeof $scope.cities[i]=='undefined')
      return; //last one 
      
      console.log("ajax to "+  $scope.cities[i].url);
      $http.get($scope.cities[i].url).then( getUrl(i+1) );
  };
  
  getUrl(0);//start 
  
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="main">
</div>
angular 2+ Promises, Observable and async pipe

angular 2+ Promises, Observable and async pipe


By : Ivan Snegon
Date : March 29 2020, 07:55 AM
it should still fix some issue This is a perfect use case for the do or map operator depending on what you're actually trying to achieve:
code :
this.settings = this.settingsService.getSettings().do(settings => this.doSomething(settings));
this.settings = this.settingsService.getSettings().map(settings => this.transformSettings(settings));
private settingsSource = new BehaviorSubject(null);
settings$ = this.settingsSource.asObservable().filter(e => !!e); //this prevents the initial null value from being sent
loadSettings() {
    this.http.get('settings').map(r => r.json()).subscribe(this.settingsSource);
}
constructor(private http: HttpClient) {
  this.loadSettings();
}
angular-file-upload async filter in angularjs

angular-file-upload async filter in angularjs


By : kate
Date : March 29 2020, 07:55 AM
Any of those help
I got the solution for the promise implementation. I used deferred promise & it worked for me. And at this time, also found quick parser - PapaParse for csv parsing.
code :
uploader.filters.push({
    name: 'fileTemplateFilter',
    fn: function(item /*{File|FileLikeObject}*/ , options, deferred) {
        vm.tableHeaders = undefined;
        vm.fileHeaders = undefined;
        var getCsvHeaders = function() {
            // return $http.get('app/pages/utilities/inventoryMapper/csvHeader.csv')
            return $http.post(csvHeadersUrl + vm.vendorWithSearchItem.selected.vendorid + '&fileName=' + item.name)
                .then(function(success) {
                    vm.tableHeaders = success.data;
                    return vm.tableHeaders;
                }, function(error) {
                    vm.tableHeaders = undefined;
                    throw error.status + " : " + error.data;
                }).catch(function(e){
                    return false;
                });
        }

        var getFileHeaders = function() {
            var defer = $q.defer();
            Papa.parse(item, {
                worker: true,
                skipEmptyLines: true,
                step: function(results, parser) {
                    parser.abort();
                    vm.fileHeaders = results.data[0] || undefined;
                    results = null;
                    defer.resolve(vm.fileHeaders);
                },
                complete: function(results){
                    results = null;
                }
            });
            return defer.promise;
        }

        $q.all([getCsvHeaders(), getFileHeaders()]).then(function() {
            if(vm.fileHeaders && vm.tableHeaders) {
                var is_same = (vm.fileHeaders.length == vm.tableHeaders.length) && vm.fileHeaders.every(function(element, index) {
                    return element === vm.tableHeaders[index];
                });
                if(is_same == true) {
                    deferred.resolve(is_same);
                } else {
                    toastr.error('file template doesn\'t match for this file - ' + item.name + ' ...!', 'Error');
                    deferred.reject(false);
                }
            } else {
                deferred.reject(false);
            }
        }, function(error) {
            deferred.reject(error);
        })

        return deferred.promise;
    }
});
Angular 8 - How to use Promises and Async/Await

Angular 8 - How to use Promises and Async/Await


By : Terry Mckee
Date : October 05 2020, 08:00 AM
With these it helps I keep trying to use tutorials but can't seem to figure out how to use Promises or async await. , You can use await operator like that:
code :
async getAsyncData() {
    this.asyncResult = await this.httpclient.get(this.URL).toPromise();
    console.log(this.asyncResult);
}
Related Posts Related Posts :
  • javascript - explanation request of a behaviour
  • Converting String into date format in JS
  • Choose element Angular
  • Display background grid by using image with CSS
  • Call function from another Controller in another file AngularJS
  • How to change texture in Gera library?
  • When trying to use windows.location.href , the values of $_POST[''] is lost
  • jQuery click action on appended item
  • NodeJS & Socket.IO: Emit a request event and get the response, when/where should I bind the listener?
  • 4-digit form on bootstrap modal
  • Prevent characters like quotation marks from input
  • Sign in option creation using jsp and oracle database
  • use socket.io in my controller with yeoman
  • What happens under the hood to prevent calling a bound method changing the this object?
  • issue with jquery .append function
  • Is it possible to EventHandle every GET request a page makes via Javascript?
  • How to select class with ng-if
  • Cannot communicate with websocket. Autobahn: received HELLO message, and session is not yet established
  • Socket.io - Cannot connect to client
  • Load Accordian Panel on click rather than page load
  • How to register async middleware module within express.js app?
  • JS / Cannot read property 'push' of undefined
  • how to make jquery plugin?
  • MATH reverting rotated coordinates
  • Add an expandable text box to every post
  • What was the rationale behind having the receiver in functions default to the global object?
  • JavaScript chaining many function
  • while loop over takes the each method
  • What are the difference between $(document).bind('ready', function) and $(document).ready(function() {})
  • cut the string in javascript
  • Tool tip not working on text area bootstrap
  • AngularJS: how to activate first non zero item in ngRepeat?
  • Pattern for "column total" of an array of arrays
  • Any selector using * failed in my case
  • Uncaught ReferenceError: app is not defined in Angularjs
  • Unit testing controller which has a $state.go method in controller
  • Use of Meteor-ui-progress-circle (accessing to Template variables created in the HTML)
  • JavaScript: Google maps mapOptions?
  • How do I track Universal Analytics events through Google Tag Manager?
  • Firefox Scrolling Bug When Changing :after Contents
  • Drop down list does not work
  • Display month and year specific datepicker in jquery
  • How to show BAr graph rather than line graph in High Stoch Chart
  • Accessing Angular $Scope in web workers
  • How to convert JavaScript(UnityScript) to C# and implement a low pass filter?
  • Need a logic to implement select button value via onchange event
  • redirect in codeigniter using ajax function
  • How to populate this form data and post it with jquery
  • Retrive value from array id in js function
  • angularjs $index when ng-hide with ng-repeat
  • ExtJS TaskRunner
  • Progress bar not hiding after fetching values via AJAX in JavaScript
  • Pop up window code fails
  • how to make dynamic javascript array with key and value group
  • Implement Facebook API login with reactjs
  • What is the meaning of sign ':' in javascript
  • Change all id's in HTMLDivElement using jQuery
  • load multiple pages from different domain in different divs using javascript
  • Could Not Resolve Host github.com
  • jQuery "Chosen" on-filter event?
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org