【发布时间】: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