简体   繁体   中英

How to pass variable reference to Observable subscription

I'm trying to get tweets from Twitter, and then get the hashtags from those tweets and get images from Flickr.

I want the tweets and images to be united together. However, see the console logs at the end. I expect the first one will output the current tweet and the second will output the images retrieved for this tweet.

However, what happens is that console.log(tweets[i]) always prints out the last tweet in the list, while console.log(results) prints the current results (ie every flickr result is printed).

By the way, the tweets and flicks are being retrieved from a json file for now.

tweets$.subscribe((tweets) => {
            for (var i in tweets) {
                var hashtags = tweets[i].entities.hashtags;
                for (var j in hashtags) {
                    var flicks$ = this.flickrService.getImagesMock(hashtag[j]);
                    flicks$.subscribe((results) => {
                        console.log(tweets[i]);
                        console.log(results);
                    });
                }
            }
        });

So my question is, how do I get the tweets[i] in the $flicks.subscribe to refer to the i that was in use when the subscription was created?

I guess it's a clasical problem with scope in async js.

for (var i in tweets) {
    (function(index) {
        var hashtags = tweets[index].entities.hashtags;
        for (var j in hashtags) {
            var flicks$ = this.flickrService.getImagesMock(hashtag[j]);
            flicks$.subscribe((results) => {
                console.log(tweets[index]);
                console.log(results);
            });
        }        
    })(i);
}

Basically, in your example nested subscribe is executed after first loop is already finished.

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