我在用角度
Core/Feature/Shared
模块模式。
什么时候?
CoreComponent
(应用程序的主页)呈现时
DataStorageService
的构造函数(用于
核心成分
的构造函数)被多次调用(每次调用构造函数时都会导致AJAX调用)
请不要将我的问题标记为重复问题,因为我的问题与以前在这里提出和回答的类似问题有点不同。
我附上了我的代码来说明我的意思(为了简单起见,我把它缩短了)。
核心/共享模块.ts
@NgModule({
declarations: [...],
imports: [...],
exports: [... ],
})
export class SharedModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: SharedModule,
providers: [XHRService, DataStorageService]
};
}
}
共享/服务/数据存储.service.ts
@Injectable()
export class DataStorageService {
constructor(private xhr: XHRService) {
this.loadEvents()
}
public loadOrigination = () => this.xhr.getOriginationsList().subscribe(this.originationsSource);
public loadEvents = () => this.xhr.getEventsList().subscribe(this.eventsSource);
private eventsSource = new BehaviorSubject(null);
private originationsSource = new BehaviorSubject(null);
public originations$ = this.originationsSource.asObservable();
public events$ = this.eventsSource.asObservable();
}
应用模块.ts
@NgModule({
declarations: [...],
imports: [
SharedModule.forRoot(),
...
],
providers: [...],
bootstrap: [AppComponent]
})
export class AppModule { }
核心/核心模块.ts
@NgModule({
declarations:
[
CoreComponent,
...
],
exports: [
CoreComponent
],
imports: [
CoreRoutingModule,
SharedModule
...
],
})
export class CoreModule { }
核心/核心组件.ts
@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.scss']
})
export class DashboardComponent implements{
constructor(public dataStorageService : DataStorageService) { }
}