Noo*_*med 5 javascript promise rxjs es6-promise angular
我在从 observable 内部分配对类的全局变量的响应时遇到了一个奇怪的问题。所以我的程序逻辑如下:
从弹性搜索中获取最新的播放列表 ID(我使用类型定义文件中的弹性搜索)。这将返回一个 PromiseLike,我将一个 then 操作符连接到它。
在承诺解决方案中,我进行了另一个 http get 调用(即一个可观察的)
在 Observable 订阅中,我将来自服务器的响应分配给我的全局数组。
代码工作正常,我得到了应有的响应,但我无法将变量分配给全局变量。
这是我的代码:
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(); 
        });
    }
| 归档时间: | 
 | 
| 查看次数: | 1718 次 | 
| 最近记录: |