我正在研究 Angular 5 单例服务。在我看来,我按照指南做了所有事情,不幸的是我的服务不是单例。每个组件似乎都在服务实例上。 我的代码如下所示:
应用模块:
import { StarService } from './star-service/star-service'
import { StarSearchComponent } from './star-search/star-search.component'
import { StarReportComponent } from './star-report/star-report.component';
@NgModule({
imports: [
BrowserModule,
FormsModule,
AppRoutingModule
],
declarations: [
AppComponent,
StarSearchComponent,
StarReportComponent
],
providers: [StarService
],
bootstrap: [AppComponent]
})
export class AppModule {
}
服务:
import { Injectable } from '@angular/core';
import { log } from 'util';
@Injectable()
export class StarService {
public Param: string;
constructor() {
this.Param = "Not Set";
console.log("Service Instance created");
}
}
星级报告组件
import { Component, OnInit } from '@angular/core';
import { StarService } from '../star-service/star-service'
@Component({
selector: 'app-star-report',
templateUrl: '<p>{{getReport}}</p>',
styleUrls: ['./star-report.component.css']
})
export class StarReportComponent implements OnInit {
constructor(private starService: StarService) { }
ngOnInit() {
this.starService.Param = "Report";
}
get getReport(): string
{
return this.starService.Param;
}
}
搜星组件
import { Component, OnInit } from '@angular/core';
import { StarService } from '../star-service/star-service'
@Component({
selector: 'app-star-search',
templateUrl: './star-search.component.html',
styleUrls: ['./star-search.component.css']
})
export class StarSearchComponent implements OnInit {
constructor(private starService: StarService) { }
ngOnInit() {
}
get getSearch(): string
{
return this.starService.Param;
}
}
现在,每次我切换组件时,我的控制台都会显示“已创建服务实例”。 此外,每个组件都显示错误的文本。我相信,当创建 StarReportComponent 时,它会切换 starService.Param = "Report"并且它将保留在那里。 不幸的是,当调用 StarSearchComponent 时,它显示默认的“未设置”。为什么?为什么单例不在这里工作? 谢谢
最佳答案
我为这个问题苦苦挣扎了很长一段时间。我想要一个单例,每当我从一个链接路由到另一个链接时,都会重新创建我希望成为单例的服务。最后的解决方案是更改导航链接:
来自:
<a href="/customers">Customers</a>
收件人:
<a routerLink="/customers">Customers</a>
我已经从关于单例的 Angular 文档中 fork 了链接,以删除 commonmodule 和 sharedmodule 的使用,以证明这不是导致问题的原因。尽管我同意使用 commonmodule 和 sharedmodule 使模块更加模块化。
https://stackblitz.com/edit/angular-uxbbdx
我有类似于示例的延迟加载模块。如果这不能为您解决问题,请告诉我。我已经解决这个问题很长时间了,可能会通过再次重现这个问题来提供帮助。
关于Angular 5服务作为单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47943377/