2016-11-22 79 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