我正在使用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不同,其中下载的数据被分配给回调函数中的参数,因此您会感到困惑。
注意参数的名称和大小写,看看这里涉及两个映射,一个在调用者与$ resource对象和对象本身之间,另一个在此对象和它构造下载的url之间实际数据。