2017-09-18 59 views
1

在我的項目中,我有一個從NeDB加載數據的服務。爲此我有一個方法getData()。在我的組件中,使用ngOnInit()鉤子,我調用這個方法。回調函數使用promise但不可觀察

問題出在哪裏。

如果getData()使用承諾一切按預期工作,並在我的應用程序的啓動我有一個查詢的結果加載和顯示的數據庫。

的getData()使用承諾

import { Injectable } from '@angular/core'; 
import { Observable } from 'rxjs/Rx'; 

import * as Datastore from 'nedb'; 
import * as path from 'path'; 

@Injectable() 
export class SearchService { 
db: any; 
    constructor() { 
    this.db = new Datastore({ 
     filename: path.resolve('src/assets/db.json'), 
     autoload: true, 
    }); 
    } 

    getData(){ 
    return new Promise((resolve, reject) => { 
     this.db.find({}, (err, docs) => { 
     if (err) reject(err); 
     resolve(docs); 
     }); 
    }) 
    } 

} 

但是,如果我試圖做到這一點使用觀測沒有被加載和顯示(傳遞給用戶的結果是undefined)。

的getData()使用觀測

getDataObs(){ 
    return new Observable(subscriber => { 
     this.db.find({}, (err, docs) => { 
     if (err) subscriber.error(err); 
     subscriber.next(docs); 
     }) 
    }) 
    } 

應用組件

import { Component, OnInit } from '@angular/core'; 
import { SearchService } from './search_service/search.service'; 
import { Observable } from 'rxjs/Observable'; 
import * as Datastore from 'nedb'; 
import * as electron from 'electron'; 
import * as path from 'path'; 

@Component({ 
    selector: 'app-root', 
    templateUrl: './app.component.html', 
    styleUrls: ['./app.component.css'], 
    providers: [SearchService] 
}) 
export class AppComponent implements OnInit { 
    title = 'app'; 
    datum; 
    res; 
    constructor(private searchService: SearchService){ } 
    ngOnInit(){ 
    this.getData(); 
    this.res = this.searchService.getDataObs(); 
    } 

    getData(){ 
    this.searchService.getData().then(res => this.datum = res); 
    } 
} 

我讓我的應用程序在啓動時 enter image description here

任何提示上爲什麼發生這種情況?我不認爲這是正常的行爲,並且認爲它與我創建可觀察的方式有關。我已閱讀bindCallback()運算符,其功能似乎是我在這裏需要的,因爲db.find()是一個回調函數,但我無法正確實現它。

對不起

編輯亂碼並在此先感謝 - 編輯 HTML

<!--The whole content below can be removed with the new code.--> 
<div style="text-align:center"> 
    <h1> 
    Welcome to {{title}}!! 
    Data: {{datum}} 
    Res: {{res | async}} 
    </h1> 

- 如果我添加getDataObs()方法按鈕,或稱之爲後100左右毫秒啓動它按預期返回查詢。

+0

您是否在html –

+0

@SachilaRanawaka中使用'json'過濾器。我只是試圖讓它現在工作。它看起來並不重要。但我已經添加了HTML問題的清晰度 –

+0

你需要使用像'{datum | json}'在html模板中,如果可能的話,你也可以通過控制檯日誌記錄來檢查值 –

回答

0
this.res = this.searchService.getDataObs(); 

這個表達式只是將返回一個可觀察實例「資源」,你可能需要做的是訂閱這個觀察到的,設置成功回調的反應是什麼。正如你所提到的那樣,當你在幾秒鐘後觸發它時正常工作,因爲到那時通話完成。

this.searchService.getDataObs().subscribe(res => this.res = res) 

一個可觀察到的相同的承諾與您的主線程異步分離。

+0

據我所知,'async'管道接受observable並訂閱它。這就是爲什麼我沒有在代碼 –

+0

中訂閱'getDataObs()'的原因你可以嘗試將返回類型指定爲Observable以getDataObs()。像這樣的getDataObs():Observable {} –

+0

試圖這樣做。結果仍然是一樣的 –