如何使我的angular2应用程序功能工作异步

时间:2017-07-20 10:45:17

标签: angular

我有一个应该读取json文件的ng2应用程序,然后使用结果将文件数据写入websql db。

在app.compopnent.ts构造函数中的

我创建了DatabaseService:

constructor(private dbservice : DatabaseService ) 

在DatabaseService构造函数中我需要检查websql db是否与我的json文件是最新的,如果不是我更新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);
        }
  );
 }...

在app.compopnent.ts构造函数中我调用

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

在我开始连接数据库之前

问题是dbservice.MDataFileVersion没有准备好值。

如何同步?

1 个答案:

答案 0 :(得分:0)

在您的应用程序组件中,您应该订阅数据库服务中的observable,然后获取/设置/使用其数据。

DBService:

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

应用程序组件:

...{
this.dbService.getVersion().subscribe( response=> {
  console.log(response.version);
...
}
相关问题