在Angular中解析的承诺之后调用其他服务函数

时间:2015-06-17 16:01:07

标签: javascript angularjs angularjs-scope angularjs-service angular-promise

在Angular中我有一项服务来访问google contacts api,然后将我的所有联系人存储到变量(StorageVar)中,以便由服务中的其他功能进行分析。

我应该在从API获取数据之前调用其中一个分析函数,我想调用getAPI函数然后(如在.then()中)运行分析函数。问题是我无法弄清楚如何访问.then()范围内的任何功能。

angular.module('API',[])
.factory('API', ['$rootScope', '$http','$q', function ($rootScope, $http, $q) {
    var StorageVar = [];
    return{
        getAPI: function(){
            //does async call, returns promise, stores data into StorageVar
        }
        Analyze: function(){
            if(StorageVar.length==0){
                 //need to get the data first
                 this.getAPI().then(function(){
                     //Analyze()
                     debugger;
                 }
            }
        }

在我的控制器中,我想要使用我的服务:

angular.module('views.local', ['API'])
.controller('localctrl',['API',function(API){
    API.Analze()
    //Callable even if the getAPI function hasn't run, so the Analyze function will take care of that.
}])

感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

这是什么意思?

/**
 * Read the file and calculate the SHA-1 checksum
 * 
 * @param file
 *            the file to read
 * @return the hex representation of the SHA-1 using uppercase chars
 * @throws FileNotFoundException
 *             if the file does not exist, is a directory rather than a
 *             regular file, or for some other reason cannot be opened for
 *             reading
 * @throws IOException
 *             if an I/O error occurs
 * @throws NoSuchAlgorithmException
 *             should never happen
 */
private static String calcSHA1(File file) throws FileNotFoundException,
        IOException, NoSuchAlgorithmException {

    MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
    try (InputStream input = new FileInputStream(file)) {

        byte[] buffer = new byte[8192];
        int len = input.read(buffer);

        while (len != -1) {
            sha1.update(buffer, 0, len);
            len = input.read(buffer);
        }

        return new HexBinaryAdapter().marshal(sha1.digest());
    }
}