简体   繁体   中英

angular component and helper service or helper class

i`m new to angular 5.

I`m trying to build the component that has lot of logic which prepares data for being able to be displayed in HTML.

As far as i know - this logic should be moved from the component to some other place in order not to trigger change tracking.(as it says here in styleguide)

I this other place should be a servie or helper class? If it service , should it be added to 'providers' of the component`s module of this component or to 'providers' of component itself?

@Component({
    selector: 'filters-bar',
    templateUrl: './filters-bar.component.html',
    styleUrls: ['./filters-bar.component.scss'],
    providers:[FiltersFromQueryService]
})

Thanks

If that class is only used in one Component use it as normal class (helper class or as I call it View Object). You can't inject them in component but you can create new instance on every initialization: this.viewObject = new ViewObject();

If it is used in multiple Components then it should be in Service so it can be injected in multiple components (initialized only once, singleton).

Providers are usualy singletone objects.

When anotated with @Injectable(), this:

@Component({})
class Cmp {
  constructor() {
    this.yourService= new YourService(...);
  }
}

...can be writen like this:

@Component({
  ..
  providers: [YourService]
})

...or like this:

@Component({})
class Cmp {
  constructor(private yourService: YourService ) {
  }
}

Singleton or not

How many places you provide an injectable determines how many instances will be created (they are only instantiated if actually requested).

If you want a single instance for your whole application, then provide an injectable only once at the root component (or with bootstrap(AppComponent, [...]) which results in the same behavior.

If you want a new instance for each component A, then add it to providers of the component A

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM