简体   繁体   English

为什么我不能在可观察对象上链接.map()函数

[英]Why can't i chain the .map() function on observables

I'm having difficulties understanding why i can't chain .map() functions on the callback of a get request. 我很难理解为什么我不能在get请求的回调上链接.map()函数。

const random = max => Math.floor((Math.random() * max) + 1);
this._http.get('https://unsplash.it/list')
    .map(response => response.json())
    .map(metaImages => metaImages.url_post)
    .subscribe(urls => {
        this.imgSrc = urls[random(urls.length)];
    });

So i break it down like this 所以我把它分解成这样

const random = max => Math.floor((Math.random() * max) + 1);
this._http.get('https://unsplash.it/list')
    .map(response => response.json())
    .subscribe(metaImages => {
        const urls = metaImages.map(url => url.post_url);
        this.imgSrc = urls[random(urls.length)];
    });

But why exactly is this? 但是,为什么呢? Thanks for helping out. 感谢您的帮助。

Make sure you don't confuse mapping an observable, which maps the observable emission stream, with mapping an array, which maps elements in the array. 确保不要将映射可观察对象(映射可观察发射流)与映射数组(映射数组中的元素)混淆。 In your case, if you want to map at the observable level before subscribing, your observable map must do an array mapping of the emission. 在您的情况下,如果要在订阅前在可观察级别进行映射,则可观察映射必须对发射进行数组映射。

const random = max => Math.floor((Math.random() * max) + 1);
this._http.get('https://unsplash.it/list')
    .map(response => response.json())

    .map(metaImages => metaImages.map(url => url.post_url))
     ^^^ MAP EMITTED ARRAY        ^^^ MAP ELTS IN EMITTED ARRAY

    .subscribe(urls => this.imgSrc = urls[random(urls.length)]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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