0

app.component.ts

export class AppComponent implements OnInit{
  title = "quogen";
  response : Response[];

  constructor (private dataService : DataService) {

  }
  ngOnInit () {
      console.log("calling init");
      return this.dataService.getQuote().subscribe(data => this.response = data);
  }
}

app.component.html

<div *ngIf="response">
  <p>{{ response['content'] }}</p>
  <p>{{ response['author'] }}</p>
</div>
<router-outlet></router-outlet>

The API is called twice from ngOnInit() as far as I know. Why is that and how can I solve this issue?

Damian-Teodor Beleș
  • 864
  • 3
  • 12
  • 26
  • 4
    Why do you return the service call? Remove `return`. As documented in Angular, `ngOnInit` should return `void`. – Damian-Teodor Beleș Mar 09 '21 at 17:14
  • Thanks for clearing things, I followed what you said, and still it didn't resolve the issue which I'm facing.. – Vinayak Bhat Mar 09 '21 at 19:20
  • You say "as far as I know", can you confirm that `console.log("calling init")` is being called twice? – RJM Mar 10 '21 at 11:24
  • 1
    I don't think that the API is called twice, but your `getQuote()` observable returns two streams. Can we see your `getQuote()` method? – Damian-Teodor Beleș Mar 10 '21 at 11:41
  • @RJM Yes, console.log("calling init") called twice – Vinayak Bhat Mar 10 '21 at 15:38
  • @Damian-TeodorBeleș getQuote(){ return this._http.get(this.apiUrl+"random"); } this is an api call which returns only one response for a call. – Vinayak Bhat Mar 10 '21 at 15:38
  • Can you do a `console.log` in the constructor to confirm that there's only one instance being created? You might also want to look at [this question](https://stackoverflow.com/questions/38787795/why-is-ngoninit-called-twice) – RJM Mar 10 '21 at 16:12
  • @RJM I did `console.log` in the constructor, and the constructor is called twice. – Vinayak Bhat Mar 10 '21 at 17:42
  • Two instances of your app component are being created then, which shouldn't be happening. You shouldn't be using `` anywhere as it is referenced in the `index.html` and you also shouldn't have any routes assigned to it. Check those and you should be able to fix your problem. – RJM Mar 11 '21 at 15:34
  • Thank you @RJM.. It worked. :) – Vinayak Bhat Mar 11 '21 at 16:56

0 Answers0