2017-07-20 4 views
0

私は、jsonファイルを読み込む必要があるng2アプリケーションを持っています。その結果を使ってwebsql dbにファイルデータを書き込みます。私のangular2アプリ関数を非同期化する方法

私はDatabaseServiceを作成app.compopnent.tsコンストラクタで

:私はwebsql DBが私のJSONファイルで最新であるかどうかを確認する必要があり、場合には、それは私ではありませんDatabaseServiceコンストラクタで

constructor(private dbservice : DatabaseService) 

websql dbを更新します。ここ

は私のサービスです。

import { Injectable } from '@angular/core'; 
import { Http, Headers,RequestOptions, Response } from '@angular/http'; 
import { Observable } from 'rxjs/Observable'; 


import "reflect-metadata"; 
import {ConnectionOptions, createConnection ,Connection} from "typeorm"; 
import {Post } from "./entity/Post"; 
import {DbMetadata} from "./entity/DbMetadata"; 

@Injectable() 
export class DatabaseService { 

private options: ConnectionOptions; 
private connection: Promise<Connection>; 

private MDataFileVersion : string ; 
private MPLanguageFileVersion : string ; 


constructor(private http: Http) 
{ 
    this.options = 
    { 
     driver: 
     { 
     type: "websql", 
     database: "test", 
     extra: { 
      version: 1, 
      description: "test database", 
      size: 2 * 1024 * 1024 
      } 
     }, 
     autoSchemaSync: true , 
     entities: [ Post , DbMetadata] // here we load all entities from entity directory] 
    }; 

    this.connection = createConnection(this.options); 

    this.setVersionFile (this.MDataFileVersion ,"./data/db/materialData.json"); 
    this.setVersionFile (this.MPLanguageFileVersion ,"./data/db/MaterialsPerLanguage.json"); 

    console.log("DatabaseService : constructor finish..." ); 
} 


private setVersionFile(resultAttribute : string ,fileName : string) 
{ 
    this.http.get(fileName) 
     .map(resp => resp.json()) 
     .subscribe(
     success => 
     { 
      if(success) 
      { 
       console.log(success); 
       resultAttribute = success.version; 
       console.log("resp.version = "+success.version); 
      } 
      else 
      { 
      console.log(" read db file error "+ fileName); 
      } 
     }, 
     error => 
     { 
      console.log(" read db file error "+ fileName + " error = "+error); 
     } 
); 
}... 

と私はDBへの接続を開始する前にapp.compopnent.tsコンストラクタで私はこの問題はdbservice.MDataFileVersionある

console.log("ngOnInit dbservice. "+this.dbservice.MDataFileVersion); 

を呼び出します値で準備ができていません。

これをどのように同期できますか?

答えて

0

あなたのアプリケーションコンポーネントでは、DBサービスのオブザーバブルに登録し、そのデータを取得/設定/使用する必要があります。

DBService:

...  
public getVersion() { 
    this.http.get(fileName) 
      .map(resp => resp.json()); 
    } 

アプリケーションコンポーネント:

...{ 
this.dbService.getVersion().subscribe(response=> { 
    console.log(response.version); 
... 
} 
関連する問題