【发布时间】:2023-03-09 09:32:01
【问题描述】:
我想要完成的是每次应用初始化只调用一次外部 API。
我有一个简单的服务,
@Injectable()
export class XService {
url = "http://api.example.com"
constructor(private _http:Http) {
}
callAnAPI(){
console.log('made an external request");
return this._http.get(url)
.map(res=>res.json());
}
}
还有两个组件,主要是appComponent
@Component({
selector: 'my-app',
template: `
<div>
Test
</div>
`
})
export class AppComponent {
isLoading = true;
results = [];
constructor(private _service: XService){
}
ngOnInit(){
Observable.forkJoin(
this._service.callAnAPI()
// some more services here
)
.subscribe(
res => {
this.results = res[0];
},
null,
() => {this.isLoading = false}
);
}
}
以及与路由一起使用的另一个组件
@Component({
template: `
<div>
I want to use the service with this component.
</div>
`
})
export class SecondComponent {
constructor(private _service: XService){
}
}
服务已初始化,Angular 在AppComponent 的初始化时命中服务器。我也想将XService 与SecondComponent 一起使用,每当我尝试从SecondComponent 再次调用服务时,(通过_service._service.callAnAPI())Angular 会命中外部API。我想尽量减少外部影响。
如何获得AppComponent在初始化时生成的数据而不是在SecondComponent再次调用服务
【问题讨论】:
标签: angular angular2-services angular2-injection