K
K
Konstantin2020-07-15 17:43:29
Angular
Konstantin, 2020-07-15 17:43:29

Organizing Angular Services?

The parent component has three components:

1. Sort
2. Filter
3. List

When the user makes changes to the Sort or Filter , the data is put into the SettingsService.

Further, this service is used in the List component - to unload the values ​​by the collected filter and sorting.

The problem is that on another page - there is a search component, which also needs to fill the SettingsService with the selected values.

As a solution - make SettingsService global. What I can’t do is because the other component has the same functionality. For which you need to save your set of settings.

How to properly organize the architecture?

You can make two copies of SettingsService and SettingsService2 - but in this case, duplicate code.

Can make two services global:

[root]
SettingsService1 extends Base {
        settingsSorting;
       settingsFilter;
}
[root]
SettingsService1 extends Base {
       settingsSorting;
       settingsFilter;
}


And in Base to take out all the logic of setting Sorting and Filters?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey P, 2020-07-23
@Junart1

The architecture is not entirely clear from the description. From what I understand, I can offer the following:
1. Place the necessary components and services in one module, then when injected into the component, it will create an instance only for this module.


When you register a provider with a specific NgModule, the same instance of a service is available to all components in that NgModule. To register at this level, use the providers property of the @NgModule() decorator,

@NgModule({
  providers: [
  BackendService,
  Logger
 ],
 ...
})

2. Make the service a singleton

By default, the Angular CLI command ng generate service registers a provider with the root injector for your service by including provider metadata in the @Injectable() decorator. The tutorial uses this method to register the provider of HeroService class definition.

@Injectable({
 providedIn: 'root',
})

and for settingsSorting and settingsFilter use hashmap
settings = {
  settingsForComp1: {
    settingsSorting,
    settingsFilter
  },
  settingsForComp2: {
    settingsSorting,
    settingsFilter
  }
}

Services are here https://angular.io/guide/architecture-services

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question