我很难理解为什么我不能在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)];
});
所以我把它分解为
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)];
});
但为什么会这样呢?谢谢你的帮忙。
答案 0 :(得分:3)
确保不要混淆映射可观察发射流的可观察映射与映射数组的映射,该数组映射数组中的元素。在您的情况下,如果您想在订阅之前在可观察级别进行映射,则您的可观察地图必须对发射进行数组映射。
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)]);