从 promise Angular 2 中设置 class 的全局变量

Set global variable of class from inside a promise Angular 2

我在将响应从可观察对象内部分配给 class 的全局变量时遇到了一个奇怪的问题。所以我的程序逻辑如下:

  1. 从弹性搜索中获取最新的播放列表 ID(我使用类型定义文件中的弹性搜索)。这个 return 是我的一个 PromiseLike 我挂钩了一个 then 运算符。

  2. 在 promise 决议中,我进行了另一个 http get 调用(即一个可观察的)

  3. 在 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的return类型是

search(params: 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*/});