Search code examples
angularionic-frameworkbindingangular2-services

Angular is it a good practice


I'm making a medium size application and I wonder about the my practice with data binding. Im passing the data directly from the service to template in this way:

      <ion-list class="list-preview ion-padding padding-top-0" lines="none" *ngIf="caseService.activeCase.value.values">
        <ion-item *ngFor="let caseItem of caseService.activeCase.value.getValues()">
          <div>
            <ion-note class="ion-float-left">{{ caseItem.label }}</ion-note>
            <ion-text class="ion-float-left">{{ caseItem.value }}</ion-text>
          </div>
        </ion-item>
      </ion-list>

Some tutorials/apps has a different approach to make it. Usually by subscribing to the service in component and then assigning the result to component variable in this way:

cases = [];
  constructor(
              public caseService: CasesService) {
  }

  ngOnInit(): void {
    this.caseService.getStructure().subscribe(cases => this.cases = cases);
  }

What do you think? Some props, cons?


Solution

  • The reason why the recommendation stands for subscribe and the return the value to local variables is because if you add the function call to the HTML template angular has to check the return value of the function this way making several calls to the function itself. Since Angular checks the return values of the function the whole change detection life cycle is triggered. If not using function calls in template but only variables Angular doesn't have to call any function only the property check is triggered. This way making the application faster and more memory efficient.