0

How can i have one service or factory receiving two parameters from many controllers?

One parameter for the url, other for the file name to be stored on the filesystem.

I will have many controllers using this service, each passing his own url and filenames that reads the url and generate a pdf.

I will always store the last downloaded pdf providing an "open last pdf" button, that will use the name parameter.

I will have a "generate new pdf" button coming from the url.

I do follow this tutorial https://blog.nraboy.com/2014/09/manage-files-in-android-and-ios-using-ionicframework/ and everything works fine.

I am using cordova file-transfer and inappbrowser cordova plugins


These sections will receive the parameters :

dirEntry.getFile("pdf-number-1.pdf",

ft.download(encodeURI("http://www.someservice.com"),p,


My attempt always trigger the message unknow pdfService provider

Wich concepts of angular i am missing ? How can i fix it ?

In services.js i have :


.service('pdfService', function($scope, $ionicLoading){

if( window.cordova && window.cordova.InAppBrowser ){
    window.open = window.cordova.InAppBrowser.open;
    console.log("InAppBrowser available");
  } else {
    console.log("InAppBrowser not available");
  }

  this.download = function() {
    $ionicLoading.show({
      template: 'Loading...'
    });
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fs) {
      fs.root.getDirectory("ExampleProject",{create: true},
          function(dirEntry) {
                dirEntry.getFile(
                    "pdf-number-1.pdf", 
                    {
                        create: true, 
                        exclusive: false
                    }, 
                    function gotFileEntry(fe) {
                        var p = fe.toURL();
                        fe.remove();
                        ft = new FileTransfer();
                        ft.download(
                            encodeURI("http://www.someservice.com"),
                            p,
                            function(entry) {
                                $ionicLoading.hide();
                                $scope.imgFile = entry.toURL();
                            },
                            function(error) {
                                $ionicLoading.hide();
                                alert("Download Error Source -> " + error.source);
                            },
                            false,
                            null
                        );                        
                    }, 
                    function() {
                        $ionicLoading.hide();
                        console.log("Get file failed");
                    }
                );
            }
        );
    },
    function() {
        $ionicLoading.hide();
        console.log("Request for filesystem failed");
    });
  }

    this.load = function() {
      $ionicLoading.show({
        template: 'Loading...'
      });

      window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fs) {
          fs.root.getDirectory(
              "ExampleProject",
              {
                  create: false
              },
              function(dirEntry) {
                  dirEntry.getFile(
                      "pdf-number-1.pdf", 
                      {
                          create: false, 
                          exclusive: false
                      }, 
                      function gotFileEntry(fe) {
                          $ionicLoading.hide();
                          $scope.imgFile = fe.toURL();
                          alert(fe.toURL());
                          window.open(fe.toURL(), '_system', 'location=no,toolbar=yes,closebuttoncaption=Close PDF,enableViewportScale=yes');
                      }, 
                      function(error) {
                          $ionicLoading.hide();
                          console.log("Error getting file");
                      }
                  );
              }
          );
      },
      function() {
          $ionicLoading.hide();
          console.log("Error requesting filesystem");
      });
    }
});

And in the controller :

.controller('SomeCtrl', function($scope, $ionicPopup, pdfService) {

 ...

pdfService.download = function(url) {
  console.log('pdfService download');
}
pdfService.load = function() {
  console.log('pdfService load');
}

1 Answer 1

2

You will need to inject the service to your controllers and call a function with the two params you want as your arguments. eg.

.service('pdfService', function(){
   var lastUrl;
   var lastFileName
   return {
      createPdf(url, fileName){
          //do processing
          lastUrl = url;
          lastFileName = fileName
      },
      loadLastPdf(){
         //use lastUrl and lastFileName
      }
   }
}

and in your controller:

.controller('SomeCtrl', function(pdfService) {
    pdfService.createPdf('http://example.com', 'file.pdf');
    // or pdfService.loadLastPdf();
}

That being said, the error you are reporting means that the DI is unable to find a service with the name pdfService to inject to your controller. This might be because you forgot to include the service.js file to your html as a script tag (if you are doing it like that) or you forgot to add it as a dependency using require (if you are using sth like browserify) or maybe if you are minifying your code since you are not using the minsafe syntax

Sign up to request clarification or add additional context in comments.

5 Comments

Thank´s mxa055! much clear now, i try to implement but see some simple sintax error : Unexpected token . at line : this.downloadPdf = function(url,fileName) { the code is here : plnkr.co/edit/ASB7LSCuCRvVLGI3Kqxf in case you want to give a help to point the syntax error. Best reards.
Yes i do include the services js as code<script src="js/services.js"></script>code . I am not sure about the way to register the service im my controller i do have : code.controller('SomeCtrl', ['$scope', 'pdfService',function($scope, $ionicPopup, pdfService ) { ... }])code
You cannot inject $scope into your service, since there is no view to glue it to. Also in your controller declaration you are missing the minsafe declaration of the $ionicPopup on your comment above. Check this out, maybe is helps plnkr.co/edit/S52j3LXvljWS2GJU7P1v?p=preview
As a improvement how can i use promisses (then) to call the load method if the downloadPdf have sucess? i do try it here on the service after the downloadPdf function link
@ÂngeloRigo I do not thing Cordoba.FileTransfer supports promises so either you should wrap it using $q service to implement a deferred promise pattern or use a promisification library like bluebird. And then you will be able to use it like pdfService.createPdf('url','filename').then(successFunction)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.