【发布时间】:2019-05-25 13:03:26
【问题描述】:
我正在通过 Angular 6 从 Web api 检索数据。
我使用组件构造函数中调用的 fetch 函数创建了一个服务,该函数将在同一页面上多次实例化。
我的问题是每次实例化我的组件时都会调用该服务。
例如我的代码如下:
服务:
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
}
}
我的组件:
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 {
}
}
与组件 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>
现在在我的应用程序上,我希望调用一次服务获取方法,并在每次实例化一个新组件时重用数据。
在 app.module.ts 中,我将 providers: [ArticleService] 放入了 @NgModule,但我收到了针对组件的每个实例的 Web api 请求。
【问题讨论】:
-
如果您想重新提出您的问题,您希望
getArticles()只被调用一次。您实际上只有一个服务实例。只需调用最相关的组件中的方法,并通过Input/services将其传递给其他人