2016-03-18 56 views
3

我試圖完成的是每個應用程序初始化只調用一次外部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的初始化上,角點擊服務器。我想要使​​用XServiceSecondComponent,只要我嘗試從SecondComponent(通過_service._service.callAnAPI())再次調用該服務,Angular會訪問外部API。我想盡量減少外部命中。

如何在SecondComponent

回答

4

再次獲得由AppComponent在初始化中產生的數據比再次呼叫服務,您可以使用do運營商爲此得到的數據第一次和重用他們下一個呼叫:

@Injectable() 
export class XService { 
    url = "http://api.example.com" 
    constructor(private _http:Http) { 

    } 

    callAnAPI(){ 
    console.log('made an external request"); 
    if (this.cachedData) { 
     return Observable.of(this.cachedData); 
    } else { 
     return this._http.get(url) 
     .map(res=>res.json()) 
     .do((data) => { 
      this.cachedData = data; 
     }); 
    } 
    } 
} 

如果要加載的數據作爲啓動,你可以調用從服務構造的callAnAPI方法。

爲了能夠使用這種方法,你需要這樣引導您的應用程序時,定義服務:

bootstrap(AppComponent, [ XService ]); 

這種方式,您將使用一個實例爲您的整個應用程序。

+1

如何以角度2.2引導此服務? – nadav

2
@Injectable() 
export class XService { 
    url = "http://api.example.com" 
    constructor(private _http:Http) { 

    } 

    callAnAPI(){ 
     if(this.data) { 
     return Observable.of(this.data); 
     } else { 
     console.log('made an external request"); 
     return this._http.get(url) 
      .map(res=>res.json()) 
      .do(res => this.data = res); 
     } 
    } 
} 
相關問題