我正在研究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 {
}
Run Code Online (Sandbox Code Playgroud)
服务:
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");
}
}
Run Code Online (Sandbox Code Playgroud)
星标报告组件
import { …Run Code Online (Sandbox Code Playgroud)