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.
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 throughInput/services