2016-11-22 225 views
4

我正在面对一个奇怪的问题,即从一个observable内部为类的全局变量分配响应。所以我的程序逻辑如下:从promise中设置类的全局变量Angular 2

  1. 从弹性搜索(我从类型定义文件中使用弹性搜索)获取最新播放列表ID。这给我一个PromiseLike,我钩了一个然后操作符。

  2. 内承诺的决定,我再拍HTTP GET调用(即一个可观察)

  3. 可观察到的认购,我给你我的全球阵列与服务器的响应。

代码工作正常,我得到的答复,因为他们应该是,但我不能将变量分配给全局。

这里是我的代码:

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

任何想法,为什么我不能为全局变量赋值?

回答

2

它看起来像this.playlistservice.listIds()返回的承诺不运行在安格拉斯区内。这就是为什么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(); 
     }); 
    } 
+0

测试目的,让我检查一下你 – noor

+0

是正确的@Gunter – noor

+1

只要我加入明确的变化检测,一切都正常,感谢您的帮助人的最低水平,被卡在这个问题上2天 – noor

1

你能尝试通过

this.playlistService.listIds() 

里面调用你的

return this.playlistService.getByIds(val) 

用第一个服务调用替换val并查看您的视图是否已更新。只是对于像

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

'函数(结果)'应该是'(results)=>'否则他不会得到设置的值;-) –

+0

是@GünterZöchbauer你是对的让我编辑它。 –

+0

顺便说一句@GünterZöchbauer你对这种方式有什么看法?我的意思是这样做是正确的? – noor