在Angular 9中使用共享服务后无法访问其他模块的问题通常是由于服务提供商的配置问题引起的。以下是一个可能的解决方法,包含代码示例:
// shared.service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class SharedService {
// 共享服务的逻辑...
}
// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { SharedService } from './shared.service';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [SharedService], // 确保在提供商数组中添加共享服务
bootstrap: [AppComponent]
})
export class AppModule { }
// other.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { OtherComponent } from './other.component';
import { SharedService } from '../shared.service';
@NgModule({
declarations: [
OtherComponent
],
imports: [
CommonModule
],
providers: [SharedService], // 确保在提供商数组中添加共享服务
exports: [OtherComponent]
})
export class OtherModule { }
// other.component.ts
import { Component, OnInit } from '@angular/core';
import { SharedService } from '../shared.service';
@Component({
selector: 'app-other',
template: `
{{ sharedService.getData() }}
`
})
export class OtherComponent implements OnInit {
constructor(private sharedService: SharedService) {}
ngOnInit() {}
}
请确保在需要访问共享服务的组件中正确注入了该服务,并在模块中正确配置了该服务的提供商。这样应该可以解决在Angular 9中使用共享服务后无法访问其他模块的问题。