javascript – 从promise Angular 2中设置类的全局变量

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

>从弹性搜索中获取最新的播放列表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的返回类型是

search(params: SearchParams): PromiseLike>;

任何想法为什么我无法为全局变量赋值?

解决方法:

看起来this.playlistservice.listIds()返回的promise不会在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(); 
        });
    }
上一篇:javascript – Rx – 基于内容拆分Observable(分组直到更改)


下一篇:Angular7里面实现 debounce search