![](/img/trans.png)
[英]Update angular2 View/global variable with data inside a promise
[英]Set global variable of class from inside a promise Angular 2
在從可觀察對象內部分配對類的全局變量的響應時,我面臨一個奇怪的問題。 所以我的程序邏輯如下:
通過彈性搜索獲取最新的播放列表ID(我使用類型定義文件中的彈性搜索)。 這給了我一個PromiseLike,我將一個then操作符掛接到它。
在promise決議中,我撥打了另一個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的返回類型為
搜索(參數:SearchParams):PromiseLike>;
為什么我不能為全局變量賦值?
看起來this.playlistservice.listIds()
返回的承諾不在Angulars區域內運行。 這就是Angular2不運行更改檢測並且無法識別更改的原因。
您可以在更改后顯式調用更改檢測:
constructor(private playlistService: PlaylistService, private cdRef:ChangeDetectorRef) {
...
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;
this.cdRef.detectChanges();
});
}
你可以嘗試通過嗎
this.playlistService.listIds()
打電話給你
return this.playlistService.getByIds(val)
將val替換為第一個服務調用,然后查看您的視圖是否已更新。 僅用於測試目的,例如
return this.playlistService.getByIds(this.playlistService.listIds())
.then((results)=>{/*rest of logic here*/});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.