我試圖完成的是每個應用程序初始化只調用一次外部API。Angular 2只在應用程序初始化時調用服務
我有一個簡單的服務,
@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){
}
}
服務被初始化並且在AppComponent
的初始化上,角點擊服務器。我想要使用XService
和SecondComponent
,只要我嘗試從SecondComponent
(通過_service._service.callAnAPI()
)再次調用該服務,Angular會訪問外部API。我想盡量減少外部命中。
如何在SecondComponent
如何以角度2.2引導此服務? – nadav