I have a messenger component, with a messages service provided in the component itself (as it needs to be component specific) as such:
@Component({
selector: "app-messenger",
templateUrl: "./messenger.page.html",
styleUrls: ["./messenger.page.scss"],
providers: [MessagesService],
})
I need to load my messages (done in the messages service) before I transition to the messenger component, and am therefore using a resolver (messagesResolver
). The messagesService
contains the messages, so the resolver needs access to a same instance of the messagesService
as the messengerComponent
.
How do I do that?
I am currently getting the error from the resolver:
NullInjectorError: R3InjectorError(MainPageModule)[MessagesResolver -> MessagesResolver -> MessagesService -> MessagesService -> MessagesService]:
NullInjectorError: No provider for MessagesService!
I understood from other Stack Overflow questions that I could Angular's Injector? However I don't know how I would go about this.
Notes on resolver:
- It is provided in root using
@Injectable({ providedIn: "root", })
- It is used in the routing of the module containing the messenger component as such:
{
path: "messenger/:chatID",
loadChildren: () =>
import("./chats/messenger/messenger.module").then((m) => m.MessengerPageModule),
resolve: {
messages: MessagesResolver,
},
},
CodePudding user response:
Using a factory will allow you to access services
, components
, properties
, functions
, etc. when a specific service is created. This allows you to modify the creation process a little bit once the service is created such as assigning a value to a property.
@Component({
providers: [{
provide: MessagesService,
useFactory: (messageResolver: MessageResolver) => messageResolver.msgService,
deps: [MessageResolver]
}]
})
export class MessengerComponent {
}