两个模块之间的全局类

时间:2017-08-23 15:06:20

标签: angular

我有一个主要模块:

app.component.html

<h1>{{globals.title}}</h1>
<router-outlet></router-outlet>

app.module.ts

@NgModule({
  imports: [
    BrowserModule,
    HomeModule,
    NotesModule,
    NgbModule,
    RouterModule.forRoot([
      {
        path         : '',
        loadChildren : './home/home.module#HomeModule'
      }, {
        path         : 'notes',
        loadChildren : './notes/notes.module#NotesModule'
      },
      {
        path         : 'error',
        component    : ErrorComponent
      },
      { path         : '**',
        redirectTo   : 'error'
      },
      { path: '**', redirectTo: '', pathMatch: 'full' }
    ])
  ],
  providers    : [homeService, Globals],
  declarations : [AppComponent, ErrorComponent],
  bootstrap    : [AppComponent]
})

export class AppModule {

app.component.ts

import { Globals } from './Globals';

@Component({
	selector    : 'app-root',
  templateUrl : './app.component.html',
  styleUrls   : ['./app.component.scss']
})
export class AppComponent {
  constructor(private globals: Globals){
  }
}

两个子模块'HomeModule'和'NotesModule'。我想为每个模块和子组件共享一些Global类。 在我看来,我需要有一个类,我可以在其中创建一些全局逻辑并为所有应用程序传递结果/变量

我为它创建了Global.ts文件:

import { Injectable } from "@angular/core";

@Injectable()
export class Globals {
  title: string = '';
}

但是当我在其他组件中更改Global的值(标题)时,它没有被更改为app.component.html:

home.component.ts

mport { Component, OnInit, Input        } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { Globals                        } from '../globals';


@Component({
  selector    : 'home-root',
  templateUrl : './home.component.html',
  styleUrls   : ['./home.component.scss']
})

export class HomeComponent {
  constructor(private newService:homeService, private globals: Globals) {
    globals.title = 'Home';
  }
}

在app.component.html中没有更改globals.title,我在其他组件中更改了

2 个答案:

答案 0 :(得分:1)

您可以使用共享模块并导入sharedModule: SharedModule

@NgModule({
 imports: [
   ...
 ],
  declarations: [
  ....
 ],
 exports: [
    ... //export component for shared
 ],
 providers: [
    Global
   ],
 })

export class SharedModule { }
HomeModule中的

@NgModule({
 imports: [
   ...
   SharedModule  //import shared
 ],
 providers: [
  ...
 ],
 declarations: [...]
})

export class HomeModule{}

答案 1 :(得分:0)

您将Globals注入私人课程。这意味着它的属性不能在模板中访问,只能在组件中访问。你在用它注入它的构造函数中将它作为public导入它,你应该能够毫无问题地访问和更改它的属性。

相关问题