2017-09-26 170 views
1

我在使緩存更簡單時遇到問題。我認爲有一個更好的方法來做到這一點。我的問題是我必須在每個get()函數中執行「緩存」代碼,這會導致代碼更長。任何人都可以幫助如何做到這一點最好的方式?謝謝。以下是我的代碼。我在代碼中做的是我在我的news.service.ts中使用get()函數從http獲取數據,並在我的新聞列表中訂閱它。從Angular 4中的HttpClient緩存數據

news.service.ts

getAllNews() { 

    if(this.newslist != null) { 
     return Observable.of(this.newslist); 
    } 

    else { 

     return this.httpClient 
     .get('http://sample.com/news') 
     .map((response => response)) 
     .do(newslist => this.newslist = newslist) 
     .catch(e => { 
      if (e.status === 401) { 
       return Observable.throw('Unauthorized');   
      } 

     }); 
    } 
    } 

新聞list.service.ts

this.subscription = this.newsService.getAllNews() 
     .subscribe(
     (data:any) => { 
      console.log(data); 
      this.newslists = data.data.data; 
     }, 
     error => { 
      this.authService.logout() 
      this.router.navigate(['signin']); 
     }); 
    } 
+0

我看不出有什麼問題... – Leo

+0

@Leo。噢好吧,我會每次使用get()函數時使用它?那將是最好的解決方案? – Joseph

+0

你的緩存究竟是什麼? 'newslists'? – Leo

回答

1

我也不太知道什麼news.service.ts之間的差異news-list.service.ts是主要的概念是,你需要分開關注。最基本的分離,你可以做的是distiguishing「數據提供者」,從「數據消費者」

數據提供

這可能是任何東西,獲取和管理數據。無論是內存中的緩存數據,服務調用等。在你的例子中,我認爲它是一個Web API客戶端/代理服務器,用於處理與新聞相關的所有事情。

如果這是一個小文件,您可以將所有與新聞相關的緩存管理移動到此文件中或創建另一個管理緩存和包裝的組件news.service.ts。該組件將從其緩存中提供數據,如果緩存不存在或已過期,則會調用news.service.ts方法。這種方式news.service.ts唯一的責任就是向API發出ajax請求。

這裏有沒有用,可觀察或錯誤處理只給你一個想法的例子...

class NewsProvider{ 

    constructor(){ 
     this.newsCache = []; 
    } 

    getNewsItemById(id){ 
     const item = this.newsCache.filter((i) => {i.id === id}); 

     if(item.length === 1) return item[0]; 

     this.newsCache = newsService.getAllNews(); 

     item = this.newsCache.filter((i) => {i.id === id}); 

     if(item.length === 1) return item[0]; 
     else return null; 
    } 
} 

數據消費者

這將是需要數據的任何組件,在一個新聞股票主頁,導航菜單中某個地方的徽章通知....可能有任何組件(或視圖)需要與新聞有關的數據。因此,這些組件/視圖不需要知道數據來自何處。

這些組件將使用「的數據提供者」,因爲數據

摘要

緩存僅需要(並且可以是)在一個位置以及網絡相關的操作

管理的主要來源
+0

謝謝,獅子座。但是我已經嘗試過這個getAll()如果(!this.news){0}這個新聞= this.httpClient,那麼這個getAll(){ \t {}。得到( 「HTTP://樣品/新聞」) \t \t \t \t \t \t \t .MAP((響應=>響應)) \t \t \t \t \t \t \t .publishReplay(1) \t \t \t \t \t \t \t .refCount(); \t} \t return this.news; } – Joseph

+0

我在service.ts中使用了.map,並在component.ts中訂閱它,以便我可以在component.html中顯示數據。我不知道這是否是最好的和最短的方式或正確的方式。 – Joseph