我正在面对一个奇怪的问题,即从一个observable内部为类的全局变量分配响应。所以我的程序逻辑如下:从promise中设置类的全局变量Angular 2
从弹性搜索(我从类型定义文件中使用弹性搜索)获取最新播放列表ID。这给我一个PromiseLike,我钩了一个然后操作符。
内承诺的决定,我再拍HTTP GET调用(即一个可观察)
可观察到的认购,我给你我的全球阵列与服务器的响应。
代码工作正常,我得到的答复,因为他们应该是,但我不能将变量分配给全局。
这里是我的代码:
import {Component, OnInit} from '@angular/core';
import {PlaylistService} from '../api/services'
@Component({
selector: 'app-playlists',
templateUrl: './playlists.component.html',
styleUrls: ['./playlists.component.css']
})
export class PlaylistsComponent implements OnInit {
public playlists: any[] = [];
constructor(private playlistService: PlaylistService) {
}
ngOnInit() {
let that = this;
this.playlistService.listIds().then((val) => { // <-- promise resolution
return this.playlistService.getByIds(val).toPromise(); // <-- http get call which i then convert to promise for simplicity
}).then((res) => { // <-- resolution of the http get call
console.log(this.playlists); <-- in this log, i get my desired results
// here is my problem, this assignment doesn't happens
this.playlists = res.data;
});
}
}
的listIds功能如下:
listIds() {
return this.api.listing('playlist').then((body) => {
let hits = body.hits.hits;
return _.keys(_.groupBy(hits, '_id'));
});
}
,这里是我的api.listing功能(弹性搜索客户端)
listing(type: string) {
let es = this.prepareES();
return es.search({
index: 'test',
_source: ["_id"],
type: type
});
}
es.search的退货类型为
search(params:SearchParams):PromiseLike>;
任何想法,为什么我不能为全局变量赋值?
测试目的,让我检查一下你 – noor
是正确的@Gunter – noor
只要我加入明确的变化检测,一切都正常,感谢您的帮助人的最低水平,被卡在这个问题上2天 – noor