Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
233 views
in Technique[技术] by (71.8m points)

Angular custom service is called in infinite loop

I am new to Angular, but I have to modify existing code.

The idea is that there is a flag (showFeature). Previously, it was just static boolean value, however now it is more complicated.

  @Input() isAccepted: boolean;
  constructor(private myService: MyService) { }
  ...

  showFeature() {
    this.myService.showFlagPromise().then((isOn: boolean) => {
      return (this.isAccepted === true) && isOn
    });
    return true;
  }

import { Injectable } from '@angular/core';
import { HttpService } from './http.service';

@Injectable({
  providedIn: 'root'
})

export class MyService {
  constructor(private http: HttpService) {
  

  }

  showFlagPromise() {
    return this.http.get<boolean>("/showFlagPromise").toPromise();
  }
}

HTML for this:

 <div [hidden]="!showFeature()"> Some button here </div>

Here I have a problem that call to this.myService.showFlagPromise is done infinitely. There is infinite calls to backend API. I understand that this is because each time Angular tries to updated value of showFeature that is used in html to show or hide some part of code.

What is the right way to fix it?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
@Input() isAccepted: boolean;
  constructor(private myService: MyService) { }
  ...

  showFlag : boolean = false;

  showFeature() {
    this.myService.showFlagPromise().then((isOn: boolean) => {
      this.showFlag = (this.isAccepted === true) && isOn;
    });
  }

Then bind your html only to this variable showFlag which by default will be false just to be safe. So by default it will not show anything and when the backend returns if it must show this flag then it will be shown.

Also Invoke showFeature() when you make any changes or when your html loads in ngOnInit()


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...