Reputation: 1741
In my Angular app, I have two components, Recordings
and Participants
, which share a common sub component, RecordingList
.
I want each of the two components to have a separate instance of the recording list. These instances should also be persistent in the sense that, when the user has visited another part of the app and returns, the lists are still present. So what I need is two instances of the recording list data structure.
There's the problem:
If I provide the RecordingListService
that contains that data structure on the global level, it will be persistent, but there will be only one instance. If I provide it at the module level, there will be an instance every time a component is created, which happens quite frequently. What I need is a way to tell the RecordingList
component to access one of the two needed instances, depending on whether it is contained in the Recordings
or the Participants
component.
Upvotes: 1
Views: 60
Reputation: 1756
Try providing the service in the component.
For example:
@Component({
selector: 'app-recordings',
templateUrl: './recordings.component.html',
providers: [ RecordingList ]
})
See documentation here: https://angular.io/guide/hierarchical-dependency-injection#providing-services-in-component
Upvotes: 0
Reputation: 486
you can provide the service by 3 ways:
in the @Injectable
like
@Injectable({
providedIn: 'root',
})
and will be avaliable for every component because is setted on the root level. second way;
@NgModule({
providers: [
BackendService,
Logger
],
...
})
this the service will be avaliable only for that ngModule(you have just one so its okey) and 3th way:
@Component({
selector: 'app-hero-list',
templateUrl: './hero-list.component.html',
providers: [ HeroService ]
})
i think if you provide it at component level(the shared subcomponent, should work)
Upvotes: 2