2017-06-13 62 views
1

我有多个应用程序在Ionic 2和3开发。他们共享相同的登录服务器,并且登录代码是相同的所有应用程序,我拆分成一个独立的git存储库。在每个应用的应用/目录,存在带有config.ts文件:角模块访问主应用程序数据

export const APPNAME = 'appname'; 
export const API = 'https://api.appname.com'; 

我包括在app.module.ts登录模块作为角模块:

@NgModule({ 
    declarations: [ 
    MainApp 
    ], 
    imports: [ 
    ... 
    LoginModule.forRoot() 
] 

和登录。 module.ts是:

import { NgModule, ModuleWithProviders } from '@angular/core'; 
import { CommonModule } from '@angular/common'; 
import { AuthService } from './auth.service'; 

@NgModule({ 
    imports: [CommonModule], 
    providers: [AuthService] 
}) 
export class LoginModule { 
    static forRoot(): ModuleWithProviders { 
     return { 
      ngModule: LoginModule, 
      providers: [AuthService] 
     } 
    } 
} 

问题是模块需要APPNAME和API地址来做登录的东西。整个模块独立于主应用程序,我作为位于src/providers/login中的git子模块添加到项目中。但是,当像LoginPage或RegisterPage模块的页面组件,我需要这些常量,我做的:

import { AuthService } from '../auth.service'; 
import { APPNAME, API } from '../../app/config'; 

@IonicPage() 
@Component({ 
    selector: 'page-login', 
    templateUrl: 'login.html' 
}) 
export class LoginPage { 

这是代码的唯一行是专门引用主要的应用程序。我想通过在主应用中通过forRoot()传递config来反转该引用,但是我不知道如何在模块的页面组件中检索它。我是否应该以某种方式将它们导入到AuthService中,然后通过页面组件中的服务访问它们?我怎样才能做到这一点?

回答

1

我终于解决了通过服务传递数据。在app.module.ts添加的应用数据:

@NgModule({ 
    declarations: [ 
    MainApp 
    ], 
    imports: [ 
    ... 
    LoginModule.forRoot({APPNAME, API}) 
] 

而在模块,将其传递给服务:

export class LoginModule { 
    static forRoot(appData: any): ModuleWithProviders { 
     return { 
      ngModule: LoginModule, 
      providers: [AuthService, { provide: 'appData', useValue: appData }] 
     } 
    } 
} 

在服务上,注入它:

@Injectable() 
export class AuthService { 

    constructor(
    @Inject('appData') public config 
) { 
    console.log(config) 
    } 
[...] 

编辑:此解决方案不能在AOT模式下工作,您需要导出为工厂功能并创建一个服务实例

export function AppConfig() { 
    return { 
     APPNAME: APPNAME, 
     API: API 
    }; 
} 

constructor(
    @Inject('appData') _appData: any 
) { 
    this.config = _appData(); 
相关问题