如何为全局websocket变量定义Angular8上下文提供程序



我在AppModule导入RecruiterAdminChatsComponent

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { RecruiterAdminChatsComponent } from './recruiter-admin-chats/recruiter-admin-chats.component';

@NgModule({
declarations: [
RecruiterAdminChatsComponent,
],
imports: [
CommonModule,
],
})
export class AppModule {}

我在app.component.ts中定义了套接字服务,如下所示

import { Component } from '@angular/core';
import { SocketService } from '../_services';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent {
constructor( private socketService: SocketService) {}
}

为了在子组件RecruiterAdminChatsComponent中使用socketservice,我也包括了套接字服务

import { Component } from '@angular/core';
import { SocketService } from '../_services';
@Component({
selector: 'app-recruiter-admin-chats',
templateUrl: './recruiter-admin-chats.component.html',
styleUrls: ['./recruiter-admin-chats.component.scss'],
})
export class RecruiterAdminChatsComponent {
constructor( private socketService: SocketService) {}
}

如您所见,SocketService在父组件和子组件处插入两次。我知道这是一件非常糟糕的事情。

如何使用在父级定义的socketservice变量,就像使用react上下文一样?

您应该将SocketService移动到AppModule中的providers部分下。它将使SocketService以Singleton的形式注入。

@NgModule({
declarations: [
RecruiterAdminChatsComponent,
],
imports: [
CommonModule,
],
providers: [
SocketService
]
})
export class AppModule {}

此外,应添加SocketService@Injectable

@Injectable()
export class SocketService {
}

相关内容

  • 没有找到相关文章

最新更新