How can I cache some data in angular 4 service?

2019-08-02 02:02发布

问题:

I have a service that I call to pull some data from my rest service. I have an object that I set inside my service with the result from the rest call. The problem is that when I call the get function to return the object I always get undefined. I currently have the call to my service on the application root onInit function.

Any help on how I could load this data and store on the object so next time I need to access it I do not need to make a remote call to my rest service?

Here is my service

    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();
    });
  }
}

Thanks for the help.

回答1:

you can use Observable Of in your function. it will store your data in side service next time it will use exising data.

sample code

 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);
        }
    }