roomcayz
roomcayz

Reputation: 2564

Angular Directive initialization good practices

I'm wondering where should I initialize component or directive complex properties like observables, form-related things or even some synchronous code which would require some time and resources to execute

So let's say I've got the same component in two versions:

@Component({})
class ExampleComponent {
  // initialization in class body or constructor
  users$ = this.store.select(selectUsers);
  constructor(
    protected store: Store<any>,
  ) { }
}

@Component({})
class ExampleComponent implements OnInit {
  users$: Observable<User[]>;
  constructor(
    protected store: Store<any>,
  ) { }
  // initialization on component init
  ngOnInit() {
    this.users$ = this.store.select(selectUsers);
  }
}

which version is more efficient? what are advantages and disadvantages of each?

Upvotes: 0

Views: 646

Answers (1)

Suren Srapyan
Suren Srapyan

Reputation: 68665

At initialization stage it is preferable to make requests at the ngOnInit life cycle event handler - maybe you need some @Input parameters that are going to be passed to the component and be used in the requests - so this ones will be available only at the ngOnInit and requests must go there.

If you have just a component that haven't any @Input parameters and is not related to other components, you can use the first version, but also in this case (if you haven't any parameters) it is a common style to make requests in the ngOnInit. So I advise to have a common style and use the second version. What about efficiency - they are the same - your variable is created at the same time and a value is assigned to it only calling this.store.select(selectUsers).

Upvotes: 1

Related Questions