刚刚开始使用Angular 8。 我目前正在尝试为复杂的项目创建用户界面。
顶部导航栏应代表用户当前所处的模式。(例如后端操作或支持系统,...可以选择代表不同的模块)。
我正在尝试在自己的模块中实现所有功能,因为它们可以由独立团队开发(将来)。因此,我将设计中的所有内容都移至了应用程序组件。 (布局),而模块之间共享的服务则位于共享的模块中。
这是反映一个第一个共享服务属性的部分:
模板:
<nav class="topBar navbar default-layout col-lg-12 p-0 fixed-top d-flex flex-row {{ getLocation() }}">
...
</nav>
component.ts
...
constructor(private frameworkService:FrameworkService) {
this.fms = frameworkService;
...
}
public getLocation(){
return this.fms.getLocation();
}
ngOnInit() {
}
}
共享模块:
import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {FrameworkService} from "./services/framework/framework.service";
@NgModule({
declarations: [],
imports: [
CommonModule
],
providers: [
FrameworkService
]
})
export class SharedModule {
}
framework.service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class FrameworkService {
private _location:string = '';
getLocation(): string {
console.log('getter');
console.log(this._location);
return this._location;
}
setLocation(value: string) {
this._location = value;
console.log('setter');
console.log(value);
console.log(this._location);
}
constructor() {
this._location = 'bg-backend';
}
}
在一个模块中,我试图这样称呼它:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { BackendRoutingModule } from './backend-routing.module';
import {MainComponent} from "./main/main.component";
import {SharedModule} from "../shared/shared.module";
import {FrameworkService} from "../shared/services/framework/framework.service";
@NgModule({
declarations: [
MainComponent
],
imports: [
CommonModule,
BackendRoutingModule,
SharedModule
]
})
export class BackendModule {
constructor(FrameworkService: FrameworkService){
FrameworkService.setLocation('bg-backend');
}
}
据我所知,我遇到了一个问题,即它没有使用单例模式(正如我期望的那样),而是使用了多实例方法。谁可以解决此问题。我看过的几页并没有真正帮助我,或者只是让我感到困惑。我目前还需要找出的是谁根据活动模块来设置值。 感谢您的帮助
:-)
克里斯
答案 0 :(得分:0)
最后,它没有按预期工作。 我发现每个会话都会打开此服务的新实例。 因此,我要做的就是将所需的信息存储在本地存储中,并在静态庄园中访问它。
感谢您的帮助:-)