简体   繁体   中英

$resource function parameters in forEach AngularJS

In this function I am retrieving every album from a list of albums:

options.albumsList.forEach(function (id) {
    var promise = $resource('https://api.imgur.com/3/album/:album',{album:id},{
        get:{
            headers:{'Authorization':'Client-ID '+ options.apiKey},
            method:'GET'
        }        
    }).get().$then(
        function(value){
            albums.push(value);
        },
        function(err){
            console.log(err);
        }
    );
    prom.push(promise);
});
$q.all(prom).then(function () {
    console.log(albums);
});

What you will notice is :album is dependant on each id in albumList

This means if I wanted to assign the resource call to a reusable object like:

var call = $resource('https://api.imgur.com/3/album/:album',{album:id},{
        get:{
            headers:{'Authorization':'Client-ID '+ options.apiKey},
            method:'GET'
        }        
    });

And then wrap it with:

options.albumsList.forEach(function (album) {
    //Can no longer pass album id to each call
    var promise = call.get().$then(
        function(value){
            albums.push(value);
        },
        function(err){
            console.log(err);
        }
    );
    prom.push(promise);
});
$q.all(prom).then(function () {
    console.log(albums);
});

I can no longer pass the album id to each :album

Is there a way around this?

资源文件 (向下滚动到返回段),貌似你可以传递一个参数来get ,将取代在URL中的价值。

var promise = call.get({album: album.id})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM