从promise Angular 2

时间:2016-11-22 10:40:57

标签: javascript angular promise rxjs es6-promise

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

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

  2. 在承诺解决方案中,我再进行一次http get调用(即可观察的)

  3. 在Observable订阅中,我使用服务器的响应分配我的全局数组。

  4. 代码工作正常,我得到的答案应该是,但我不能将变量分配给全局变量。

    这是我的代码:

    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&gt ;;

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

2 个答案:

答案 0 :(得分:2)

看起来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(); 
        });
    }

答案 1 :(得分:1)

你可以尝试传递

this.playlistService.listIds() 

在你的

内打电话
return this.playlistService.getByIds(val)

用第一次服务调用替换val,看看你的视图是否得到更新。仅用于测试目的,如

return this.playlistService.getByIds(this.playlistService.listIds())
       .then((results)=>{/*rest of logic here*/});