我正在面對一個奇怪的問題,即從一個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