【问题标题】:Global class between two modules两个模块之间的全局类
【发布时间】:2017-08-23 23:24:30
【问题描述】:

我有一个主要模块:

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.ts 文件:

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

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

但是当我在其他组件中更改 Global 的 value(title) 时,它没有更改的是 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 没有更改,但我在其他组件中更改了它

【问题讨论】:

  • 你使用延迟加载的模块吗?
  • 可能不会,Global.ts在任何路线上都可以看到
  • 呃,是的,您使用的是延迟加载模块:loadChildren : './notes/notes.module#NotesModule'。那是延迟加载。
  • 你能分享app.component.ts吗?另外,如果您直接使用globals.title,为什么HomeComponent 有一个属性title

标签: angular


【解决方案1】:

您可以使用共享模块并导入 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{}

【讨论】:

    【解决方案2】:

    您将 Globals 作为私有类注入。这意味着它的属性将无法在模板中访问,只能在组件中访问。如果您在用于注入它的构造函数中将其作为公共导入,您应该能够毫无问题地访问和更改其属性。

    【讨论】:

      猜你喜欢
      • 2010-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-03
      • 1970-01-01
      相关资源
      最近更新 更多