5

Template

<pre *ngIf="isAdmin()">{{email|json}} - {{user|json}}</pre>

Component

isAdmin() {
    console.log('isAdmin: ', this.bcAuthService.isAdmin());
    return this.bcAuthService.isAdmin();
}

Service

isAdmin() {
    return this.admins.includes(localStorage.getItem("email"));
}

Problem

the function in the component keeps printing several times. Why? Is this wrong? What is a better way?

enter image description here

Omar
  • 2,726
  • 2
  • 32
  • 65
  • 2
    Template methods will almost always be called multiple times. The same is true for `*ngFor` that it is iterated over multiple times. If you have something that executes an expensive call then you should cache the result and return that either in the method or use ngOnInit to retrieve/calculate the values and set them in your component. – Igor Jun 20 '18 at 21:40

3 Answers3

8

Template methods will almost always be called multiple times. The same is true for *ngFor that it is iterated over multiple times. If you have something that executes an expensive call then you should cache the result and return that either in the method or use ngOnInit to retrieve/calculate the values and set them in your component.

Template code

<pre *ngIf="isAdmin">{{email|json}} - {{user|json}}</pre>

Component

export class MyComponent implements OnInit {

    isAdmin: boolean;

    ngOnInit() {
        this.isAdmin = this.bcAuthService.isAdmin();
        console.log('isAdmin: ', this.isAdmin);
    }
}
Igor
  • 60,821
  • 10
  • 100
  • 175
2

after finding this why *ngIf in angular 2 always is executing when use function?

i resolved the problem by

component

ngOnInit() {
    this.is_admin();
}
is_admin() {
    this.isAdmin = this.bcAuthService.isAdmin();
}

html

<pre *ngIf="isAdmin">{{email|json}} - {{user|json}}</pre>
Omar
  • 2,726
  • 2
  • 32
  • 65
0

Now you don't have method(member instead) and it's not spamming "isAdmin: true" but it's not means that problem is resolved.

You can be interested in changeDetection of the component and ChangeDetectorRef to actually tell angular when isAdmin is changed to update template(detectChanges).

Buczkowski
  • 2,296
  • 12
  • 18