how to make HTTP call only once on component creation

Multi tool use
Multi tool use












1














I am retrieving data from a web api through angular 6.



I created a service with a fetch function that is called in a component constructor, which will be instanciated multiple times on the same page.



My problem is that the service is called each time my component is instanciated.



For example my code is the following :



Service :



import { Injectable } from '@angular/core';
import { Article } from '../../Classes/article'
import { Observable } from 'rxjs';
import { MessageService } from '../../Services/message/message.service'
import { HttpClient } from '@angular/common/http'


@Injectable({
providedIn: 'root'
})
export class ArticleService {

Values: Observable<Article> ;


constructor(private messageService: MessageService, private http : HttpClient)
{
this.buildArticles()
}

private articlesUrl = 'http://localhost:63138/v/Article'

private buildArticles(): void {
this.Values = this.http.get<Article>(this.articlesUrl)
}

getArticles() : Observable<Article> {
return this.Values
}
}


My component :



import { Component,OnInit, Input } from '@angular/core';
import { ArticleService } from 'src/app/Services/article/article.service';
import { Article } from 'src/app/Classes/Article'

@Component({
selector: 'app-article',
templateUrl: './article.component.html',
styleUrls: ['./article.component.scss'],
})

export class ArticleComponent implements OnInit {

@Input() artId :number;


constructor( private articleService : ArticleService) {
articleService.getArticles().subscribe(x=> this.articles = x);
}
articles : Article;
ngOnInit(): void {
}
}


with the component html :



<mat-form-field>
<mat-select [(ngModel)]="artId" >
<mat-option *ngFor="let art of articles" [value]="art.Id">
{{art.Libelle1}}</mat-option>
</mat-select>
</mat-form-field>


Now on my app I would like the service fetch method to be called once, and reuse the data each time I instanciate a new component.



In the app.module.ts, I put providers: [ArticleService] in @NgModule but I get a request to my web api for each instance of the component.










share|improve this question




















  • 1




    If you would like to re-word your question, you want the getArticles() to be called only once. You actually have only one instance of the service. Just call the method in the top most relevant component and pass it to others through Input/services
    – xyz
    Dec 27 at 13:47
















1














I am retrieving data from a web api through angular 6.



I created a service with a fetch function that is called in a component constructor, which will be instanciated multiple times on the same page.



My problem is that the service is called each time my component is instanciated.



For example my code is the following :



Service :



import { Injectable } from '@angular/core';
import { Article } from '../../Classes/article'
import { Observable } from 'rxjs';
import { MessageService } from '../../Services/message/message.service'
import { HttpClient } from '@angular/common/http'


@Injectable({
providedIn: 'root'
})
export class ArticleService {

Values: Observable<Article> ;


constructor(private messageService: MessageService, private http : HttpClient)
{
this.buildArticles()
}

private articlesUrl = 'http://localhost:63138/v/Article'

private buildArticles(): void {
this.Values = this.http.get<Article>(this.articlesUrl)
}

getArticles() : Observable<Article> {
return this.Values
}
}


My component :



import { Component,OnInit, Input } from '@angular/core';
import { ArticleService } from 'src/app/Services/article/article.service';
import { Article } from 'src/app/Classes/Article'

@Component({
selector: 'app-article',
templateUrl: './article.component.html',
styleUrls: ['./article.component.scss'],
})

export class ArticleComponent implements OnInit {

@Input() artId :number;


constructor( private articleService : ArticleService) {
articleService.getArticles().subscribe(x=> this.articles = x);
}
articles : Article;
ngOnInit(): void {
}
}


with the component html :



<mat-form-field>
<mat-select [(ngModel)]="artId" >
<mat-option *ngFor="let art of articles" [value]="art.Id">
{{art.Libelle1}}</mat-option>
</mat-select>
</mat-form-field>


Now on my app I would like the service fetch method to be called once, and reuse the data each time I instanciate a new component.



In the app.module.ts, I put providers: [ArticleService] in @NgModule but I get a request to my web api for each instance of the component.










share|improve this question




















  • 1




    If you would like to re-word your question, you want the getArticles() to be called only once. You actually have only one instance of the service. Just call the method in the top most relevant component and pass it to others through Input/services
    – xyz
    Dec 27 at 13:47














1












1








1







I am retrieving data from a web api through angular 6.



I created a service with a fetch function that is called in a component constructor, which will be instanciated multiple times on the same page.



My problem is that the service is called each time my component is instanciated.



For example my code is the following :



Service :



import { Injectable } from '@angular/core';
import { Article } from '../../Classes/article'
import { Observable } from 'rxjs';
import { MessageService } from '../../Services/message/message.service'
import { HttpClient } from '@angular/common/http'


@Injectable({
providedIn: 'root'
})
export class ArticleService {

Values: Observable<Article> ;


constructor(private messageService: MessageService, private http : HttpClient)
{
this.buildArticles()
}

private articlesUrl = 'http://localhost:63138/v/Article'

private buildArticles(): void {
this.Values = this.http.get<Article>(this.articlesUrl)
}

getArticles() : Observable<Article> {
return this.Values
}
}


My component :



import { Component,OnInit, Input } from '@angular/core';
import { ArticleService } from 'src/app/Services/article/article.service';
import { Article } from 'src/app/Classes/Article'

@Component({
selector: 'app-article',
templateUrl: './article.component.html',
styleUrls: ['./article.component.scss'],
})

export class ArticleComponent implements OnInit {

@Input() artId :number;


constructor( private articleService : ArticleService) {
articleService.getArticles().subscribe(x=> this.articles = x);
}
articles : Article;
ngOnInit(): void {
}
}


with the component html :



<mat-form-field>
<mat-select [(ngModel)]="artId" >
<mat-option *ngFor="let art of articles" [value]="art.Id">
{{art.Libelle1}}</mat-option>
</mat-select>
</mat-form-field>


Now on my app I would like the service fetch method to be called once, and reuse the data each time I instanciate a new component.



In the app.module.ts, I put providers: [ArticleService] in @NgModule but I get a request to my web api for each instance of the component.










share|improve this question















I am retrieving data from a web api through angular 6.



I created a service with a fetch function that is called in a component constructor, which will be instanciated multiple times on the same page.



My problem is that the service is called each time my component is instanciated.



For example my code is the following :



Service :



import { Injectable } from '@angular/core';
import { Article } from '../../Classes/article'
import { Observable } from 'rxjs';
import { MessageService } from '../../Services/message/message.service'
import { HttpClient } from '@angular/common/http'


@Injectable({
providedIn: 'root'
})
export class ArticleService {

Values: Observable<Article> ;


constructor(private messageService: MessageService, private http : HttpClient)
{
this.buildArticles()
}

private articlesUrl = 'http://localhost:63138/v/Article'

private buildArticles(): void {
this.Values = this.http.get<Article>(this.articlesUrl)
}

getArticles() : Observable<Article> {
return this.Values
}
}


My component :



import { Component,OnInit, Input } from '@angular/core';
import { ArticleService } from 'src/app/Services/article/article.service';
import { Article } from 'src/app/Classes/Article'

@Component({
selector: 'app-article',
templateUrl: './article.component.html',
styleUrls: ['./article.component.scss'],
})

export class ArticleComponent implements OnInit {

@Input() artId :number;


constructor( private articleService : ArticleService) {
articleService.getArticles().subscribe(x=> this.articles = x);
}
articles : Article;
ngOnInit(): void {
}
}


with the component html :



<mat-form-field>
<mat-select [(ngModel)]="artId" >
<mat-option *ngFor="let art of articles" [value]="art.Id">
{{art.Libelle1}}</mat-option>
</mat-select>
</mat-form-field>


Now on my app I would like the service fetch method to be called once, and reuse the data each time I instanciate a new component.



In the app.module.ts, I put providers: [ArticleService] in @NgModule but I get a request to my web api for each instance of the component.







angular service






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 27 at 13:53









trichetriche

25.4k42051




25.4k42051










asked Dec 27 at 13:43









hunB

355




355








  • 1




    If you would like to re-word your question, you want the getArticles() to be called only once. You actually have only one instance of the service. Just call the method in the top most relevant component and pass it to others through Input/services
    – xyz
    Dec 27 at 13:47














  • 1




    If you would like to re-word your question, you want the getArticles() to be called only once. You actually have only one instance of the service. Just call the method in the top most relevant component and pass it to others through Input/services
    – xyz
    Dec 27 at 13:47








1




1




If you would like to re-word your question, you want the getArticles() to be called only once. You actually have only one instance of the service. Just call the method in the top most relevant component and pass it to others through Input/services
– xyz
Dec 27 at 13:47




If you would like to re-word your question, you want the getArticles() to be called only once. You actually have only one instance of the service. Just call the method in the top most relevant component and pass it to others through Input/services
– xyz
Dec 27 at 13:47












2 Answers
2






active

oldest

votes


















2














Angular creates components on demand.



In your case, everytime a component is created, you make an HTTP call by using the service method to fetch your data.



The issue isn't with instances of the service (or even your component), it's the design you have chosen that doesn't suit your case.



What you need is some sort of caching. To implement that, you can use subjects :



private _cachedData: Subject<any>;
public data = this._cachedData.asObservable();

refreshData() {
this.http.get(...).subscribe(res => this._cachedData.next(res));
}

initializeData() {
if (!this._cachedData) {
this._cachedData = ,new Subject();
this.refreshData();
}
}


This is very simple, but it should do the trick. Now you can just use myService.data.subscribe() to get the cached data, and you can initialize data in your component constructor (because your service is a singleton, if you try to call it with data already cached, the service will simply ignore the request).






share|improve this answer





























    2














    By declaring your component



    @Injectable({
    providedIn: 'root'
    })


    you guarantee that it will be one instance of your service, the problem is with the fact that every time you call subscribe the entire observer chain is executed (including get). You have to do something like this:



    import { publishReplay, refCount } from 'rxjs/operators';    

    return this.http.get<Article>(this.articlesUrl)
    .pipe(
    publishReplay(),
    refCount())


    it will remit the value for every subscription.






    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53946078%2fhow-to-make-http-call-only-once-on-component-creation%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      2














      Angular creates components on demand.



      In your case, everytime a component is created, you make an HTTP call by using the service method to fetch your data.



      The issue isn't with instances of the service (or even your component), it's the design you have chosen that doesn't suit your case.



      What you need is some sort of caching. To implement that, you can use subjects :



      private _cachedData: Subject<any>;
      public data = this._cachedData.asObservable();

      refreshData() {
      this.http.get(...).subscribe(res => this._cachedData.next(res));
      }

      initializeData() {
      if (!this._cachedData) {
      this._cachedData = ,new Subject();
      this.refreshData();
      }
      }


      This is very simple, but it should do the trick. Now you can just use myService.data.subscribe() to get the cached data, and you can initialize data in your component constructor (because your service is a singleton, if you try to call it with data already cached, the service will simply ignore the request).






      share|improve this answer


























        2














        Angular creates components on demand.



        In your case, everytime a component is created, you make an HTTP call by using the service method to fetch your data.



        The issue isn't with instances of the service (or even your component), it's the design you have chosen that doesn't suit your case.



        What you need is some sort of caching. To implement that, you can use subjects :



        private _cachedData: Subject<any>;
        public data = this._cachedData.asObservable();

        refreshData() {
        this.http.get(...).subscribe(res => this._cachedData.next(res));
        }

        initializeData() {
        if (!this._cachedData) {
        this._cachedData = ,new Subject();
        this.refreshData();
        }
        }


        This is very simple, but it should do the trick. Now you can just use myService.data.subscribe() to get the cached data, and you can initialize data in your component constructor (because your service is a singleton, if you try to call it with data already cached, the service will simply ignore the request).






        share|improve this answer
























          2












          2








          2






          Angular creates components on demand.



          In your case, everytime a component is created, you make an HTTP call by using the service method to fetch your data.



          The issue isn't with instances of the service (or even your component), it's the design you have chosen that doesn't suit your case.



          What you need is some sort of caching. To implement that, you can use subjects :



          private _cachedData: Subject<any>;
          public data = this._cachedData.asObservable();

          refreshData() {
          this.http.get(...).subscribe(res => this._cachedData.next(res));
          }

          initializeData() {
          if (!this._cachedData) {
          this._cachedData = ,new Subject();
          this.refreshData();
          }
          }


          This is very simple, but it should do the trick. Now you can just use myService.data.subscribe() to get the cached data, and you can initialize data in your component constructor (because your service is a singleton, if you try to call it with data already cached, the service will simply ignore the request).






          share|improve this answer












          Angular creates components on demand.



          In your case, everytime a component is created, you make an HTTP call by using the service method to fetch your data.



          The issue isn't with instances of the service (or even your component), it's the design you have chosen that doesn't suit your case.



          What you need is some sort of caching. To implement that, you can use subjects :



          private _cachedData: Subject<any>;
          public data = this._cachedData.asObservable();

          refreshData() {
          this.http.get(...).subscribe(res => this._cachedData.next(res));
          }

          initializeData() {
          if (!this._cachedData) {
          this._cachedData = ,new Subject();
          this.refreshData();
          }
          }


          This is very simple, but it should do the trick. Now you can just use myService.data.subscribe() to get the cached data, and you can initialize data in your component constructor (because your service is a singleton, if you try to call it with data already cached, the service will simply ignore the request).







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Dec 27 at 13:58









          trichetriche

          25.4k42051




          25.4k42051

























              2














              By declaring your component



              @Injectable({
              providedIn: 'root'
              })


              you guarantee that it will be one instance of your service, the problem is with the fact that every time you call subscribe the entire observer chain is executed (including get). You have to do something like this:



              import { publishReplay, refCount } from 'rxjs/operators';    

              return this.http.get<Article>(this.articlesUrl)
              .pipe(
              publishReplay(),
              refCount())


              it will remit the value for every subscription.






              share|improve this answer




























                2














                By declaring your component



                @Injectable({
                providedIn: 'root'
                })


                you guarantee that it will be one instance of your service, the problem is with the fact that every time you call subscribe the entire observer chain is executed (including get). You have to do something like this:



                import { publishReplay, refCount } from 'rxjs/operators';    

                return this.http.get<Article>(this.articlesUrl)
                .pipe(
                publishReplay(),
                refCount())


                it will remit the value for every subscription.






                share|improve this answer


























                  2












                  2








                  2






                  By declaring your component



                  @Injectable({
                  providedIn: 'root'
                  })


                  you guarantee that it will be one instance of your service, the problem is with the fact that every time you call subscribe the entire observer chain is executed (including get). You have to do something like this:



                  import { publishReplay, refCount } from 'rxjs/operators';    

                  return this.http.get<Article>(this.articlesUrl)
                  .pipe(
                  publishReplay(),
                  refCount())


                  it will remit the value for every subscription.






                  share|improve this answer














                  By declaring your component



                  @Injectable({
                  providedIn: 'root'
                  })


                  you guarantee that it will be one instance of your service, the problem is with the fact that every time you call subscribe the entire observer chain is executed (including get). You have to do something like this:



                  import { publishReplay, refCount } from 'rxjs/operators';    

                  return this.http.get<Article>(this.articlesUrl)
                  .pipe(
                  publishReplay(),
                  refCount())


                  it will remit the value for every subscription.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Dec 27 at 13:55

























                  answered Dec 27 at 13:50









                  piotr szybicki

                  497210




                  497210






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.





                      Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                      Please pay close attention to the following guidance:


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53946078%2fhow-to-make-http-call-only-once-on-component-creation%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      IJZqoS8bzM1bQ GNVifXDWOtryvhdCAr,9nF FLDv VCTBIW4BYk3zd6f IzT 3VW ozGFeQ0ndS73
                      NS46RNVK2cdRtbFCjR1T3pZBOKC8CyVcB7iWd8fikVXNEXhLtohuTgS7FPM7KHooOusRxGAcrRgFYqINmGOAD6GnqmxmpBmxi

                      Popular posts from this blog

                      Monofisismo

                      Angular Downloading a file using contenturl with Basic Authentication

                      Olmecas