Home > Software design >  Where to define selectors with async pip in NgRx
Where to define selectors with async pip in NgRx

Time:11-13

To take advantage of async pipe we should create a selector observable in the component class. However, everybody recommends using ngOnInit() to do so:

@Component({
  selector: 'app-landing',
  templateUrl: './landing.component.html',
  styleUrls: ['./landing.component.scss']
})
export class MyComponent implements OnInit {
    person$: Observable<Person>;
    constructor(private store: Store<ApplicationState>) {}
    ngOnInit() {
        this.person$ = this.store.select(stateToCurrentPersonSelector);
    }
} 

What if we define the selector observable outside of the ngOnInit() like the following snippet. It works perfectly fine:

export class MyComponent implements OnInit {
    person$ = this.store.select(stateToCurrentPersonSelector);
    constructor(private store: Store<ApplicationState>) {}
    ngOnInit() {}
} 

CodePudding user response:

In the case of async pipe, there's no difference in term of performance.

You might think it’s better to wait for ngOnInit() to trigger the fetch of products, but here’s the deal. Steams, unlike promises, are lazy.
They don’t execute their logic until they're subscribed to.
That means there is no difference to request timing for both approaches.

You can find more info about this from here: https://twitter.com/realTomaszKula/status/1559258801261404166

  • Related