【发布时间】:2020-03-21 22:24:56
【问题描述】:
我有 2 个组件和 2 个组件之间共享的一项服务,比如说 ComponentA 和 ComponentB。应用程序工具栏的一个组件(Comp. A)和另一个组件 B 使用路由模块进行路由。这是 HTML:
<a></a>
<router-outlet></router-outlet>
之所以这样,是因为我希望工具栏始终存在,固定在顶部。 在组件 A 的 HTML 中,我可以选择应用程序的语言。在组件 BI 中有一些来自后端的内容,具体取决于所选语言。我希望当用户更改语言时,内容来自服务器,进行渲染。我正在使用该服务调用后端并渲染新内容.我的问题来了,对服务器的调用已完成并且没问题,但它从未进入订阅功能。我尝试使用共享模块(有或没有 forRoot()),我试图使服务成为模块的提供者,并将模块(AppRoutingModule)导入另一个模块(AppModule)。在这一刻,我达到了“没有服务提供者!”的地步。控制台中的错误。服务和组件的代码: 服务:
@Injectable()
export class SharedService extends GlobalHttpService<HomeSection> {
private sectionsSubject: BehaviorSubject<HomeSection[]>;
constructor(private http: HttpClient) {
super("api/path", new GlobalSerializer(HomeSection), http);
this.sectionsSubject = new BehaviorSubject<HomeSection[]>([]);
}
load() {
this.list().subscribe(res => {
this.sectionsSubject.next(res);
});
}
get content() {
return this.sectionsSubject.asObservable();
}
}
AppModule
@NgModule({
imports:[AppRoutingModule]
})
export class AppModule {}
AppRoutingModule
export function SharedServiceFactory(http: HttpClient){
return new SharedServiceFactory(http);
}
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
providers: [
{
provide: SectionService,
useFactory: SectionServiceFactory,
deps: [HttpClient]
}
]
})
export class AppRoutingModule {}
组件A:
@Component({
selector: "a",
templateUrl: ".a.component.html",
styleUrls: ["./a.component.scss"]
})
export class AComponent implements OnInit {
constructor(
public authentificationService: AuthenticationService,
private languagesService: LanguagesService,
private sharedService: SharedService
) {
}
ngOnInit() {
//other logic;
}
updateLanguage(event) {
// other logic;
this.sharedService.load();
}
组件B
@Component({
selector: "app-b",
templateUrl: "./b.component.html",
styleUrls: ["./b.component.scss"]
})
export class BComponent implements OnInit {
constructor(
private sharedService: SharedService,
) {}
ngOnInit() {
this.sharedService.load();
this.sharedService.content.subscribe(s => {
// logic
});
}
我怎样才能拥有一个 SharedService 实例,或者我可以在另一个模块中包含一个模块?
【问题讨论】:
标签: angular angular8 angular-services angular-module