Angular js 使用 $resource 下载文件并显示加载屏幕的方式

2023-12-28

我正在使用 Angular js 显示加载屏幕。它适用于除下载文件的 REST 服务之外的所有 REST 服务调用。我明白为什么它不起作用,因为下载时我没有使用 $resource; 进行任何服务调用;相反,我使用正常的方法来下载文件,因此 Angular js 代码对启动/完成服务请求没有任何控制。我尝试使用 $resource 来访问此 REST 服务,但是我从该服务获取数据,在这种情况下,加载屏幕工作正常,但不确定如何使用此数据向用户显示以角度方式下载。以下是所需的详细信息。请帮忙。

方法1使用iframe方法:

 /*Download file */
            scope.downloadFile = function (fileId) {
                //Show loading screen. (Somehow it is not working)
                scope.loadingProjectFiles=true;
                var fileDownloadURL = "/api/files/" + fileId + "/download";
                downloadURL(fileDownloadURL);
              //Hide loading screen
                scope.loadingProjectFiles=false;
            };

            var $idown;  // Keep it outside of the function, so it's initialized once.
            var downloadURL = function (url) {
                if ($idown) {
                    $idown.attr('src', url);
                } else {
                    $idown = $('<iframe>', { id: 'idown', src: url }).hide().appendTo('body');
                }
            };

方法2使用$resource(不知道如何在屏幕上显示数据以供下载)

/*Download file */
            scope.downloadFile = function (fileId) {
                //Show loading screen (Here loading screen works).  
                scope.loadingProjectFiles=true;                 
                  //File download object
                    var fileDownloadObj = new DownloadFile();
                 //Make server call to create new File
                    fileDownloadObj.$get({ fileid: fileid }, function (response) {
                        //Q? How to use the response data to display on UI as download popup
                        //Hide loading screen
                        scope.loadingProjectFiles=false;
                    });

            };

这是 $resource 服务的正确模式:

scope.downloadFile = function (fileId) {
    //Show loading screen (Here loading screen works).  
    scope.loadingProjectFiles=true;                 
    var FileResource = $resource('/api/files/:idParam', {idParam:'@id'});
    //Make server call to retrieve a file
    var yourFile = FileResource.$get({ id: fileId }, function () {
        //Now (inside this callback) the response data is loaded inside the yourFile variable
        //I know it's an ugly pattern but that's what $resource is about...
        DoSomethingWithYourFile(yourFile);
        //Hide loading screen
        scope.loadingProjectFiles=false;
    });
 };

我同意你的观点,这是一种奇怪的模式,与其他 API 不同,在其他 API 中,下载的数据被分配给回调函数中的参数,因此你会感到困惑。

注意参数的名称和大小写,看看这里涉及到两个映射,一个是 $resource 对象的调用者和对象本身之间的映射,另一个是这个对象和它构建的用于下载的 url 之间的映射实际数据。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Angular js 使用 $resource 下载文件并显示加载屏幕的方式 的相关文章

随机推荐