2017-06-19 68 views
1

我有一個服務,我打電話來從我的休息服務拉一些數據。我有一個對象,我在其他服務的結果中設置了我的服務。問題是,當我調用get函數返回對象時,我總是得到未定義的。我目前在應用程序根onInit函數中調用了我的服務。如何在角度4服務中緩存一些數據?

有關如何加載數據和存儲在對象上的任何幫助,以便下次需要訪問它時,我不需要對我的休息服務進行遠程調用?

這裏是我的服務

import { Injectable } from '@angular/core'; 
    import { Headers, RequestOptions } from '@angular/http'; 
    import { HttpinterceptorService } from './httpinterceptor.service'; 
    import { TopicStatus } from '../interfaces/topicstatus'; 
    import 'rxjs/add/operator/map'; 

    @Injectable() 
export class TopicService { 
    baseUrl: string; 
    statusObj: TopicStatus[]; 

    constructor(private http: HttpinterceptorService) { 
    this.baseUrl = '/test/restcall/'; 
    } 

    getListItems(token: string, topicType: string, topicStatus?: number) { 
    const headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded'}), 
      options = new RequestOptions({ headers: headers}); 
    let body = 'ooo=' + token + '&type=' + topicType; 
    if(topicStatus !== undefined) { 
     body += '&status=' + topicStatus; 
    } 
    return this.http.post(this.baseUrl + 'test/restcall', body, options) 
     .map((res) => res.json()); 
    } 

    getTopicStatus(token: string) { 
    const headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded'}), 
      options = new RequestOptions({ headers: headers}), 
      body = 'ooo=' + token; 

    this.http.post(this.baseUrl + 'test/restcall', body, options).map((res) => { 
     this.statusObj = res.json(); 
    }); 
    } 
} 

感謝您的幫助。

回答

2

你可以在你的函數中使用Observable Of。它會將您的數據存儲在旁邊的服務中,下次它將使用正在發佈的數據。

示例代碼

getListItems() { 

     if(this.storeInfo != null) 
     { 
      return Observable.of(this.storeInfo); 
     } 
     else 
     { 
    const headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded'}), 
       options = new RequestOptions({ headers: headers}); 
     let body = 'ooo=' + token + '&type=' + topicType; 
     if(topicStatus !== undefined) { 
      body += '&status=' + topicStatus; 
     } 
      return this.http.post(this.baseUrl + 'test/restcall', body, options) 
       .map(res => <Contact[]> res.json()) 
       .do(storeInfo => this.storeInfo = storeInfo) 
       .catch(this.handleError); 
     } 
    } 
+0

感謝該工作:)幫助 – Ennio