NgrxStore and Angular - Use the async pipe massively or subscribe just once in the constructor

前端 未结 3 934
半阙折子戏
半阙折子戏 2020-12-04 19:06

I am starting to look at ngrx Store and I see the convenience to use the Angular async pipe. At the same time I am not sure whether using the Angular async pipe massively is

3条回答
  •  自闭症患者
    2020-12-04 19:38

    Neither, you should compose your application as smart and presentation components.

    Advantages:

    • All buissness logic on the smart controller.
    • Just one subscribe
    • Reusability
    • The presentation controller has only one responsibility, only to present data and does not know from where the data come from. (loosely coupled)

    Answering the last question:

    The massive use of async pipe will affect the efficiency, because it will subscribe to every async pipe. You can notice this more if you are calling a http service, because it will call the http request for each async pipe.

    Smart Component

    @Component({
      selector: 'app-my',
      template: `
          
    `,
      styleUrls: ['./my.component.css']
    })
    export class MyComponent implements OnInit {
    
        person$: Observable;
    
        constructor(private store: Store) {}
    
        ngOnInit() {
            this.person$ = this.store.select(stateToCurrentPersonSelector);
        }
    
    }
    

    Presentation Component

    @Component({
      selector: 'app-person',
      template: `
        
    {{person.name}}
    {{person.address}}
    {{person.age}}
    `, styleUrls: ['./my.component.css'] }) export class PersonComponent implements OnInit { @Input() person: Person; constructor() {} ngOnInit() { } }

    For more info check:

    • https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0#.u27zmzf25
    • http://blog.angular-university.io/angular-2-smart-components-vs-presentation-components-whats-the-difference-when-to-use-each-and-why/

提交回复
热议问题