亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用angular2 http服務緩存結果

使用angular2 http服務緩存結果

互換的青春 2019-12-25 14:44:04
我通過服務公開了一個HTTP GET請求,并且幾個組件正在使用此數據(用戶的配置文件詳細信息)。我希望第一個組件請求實際對服務器執行HTTP GET請求并緩存結果,以便后續請求將使用緩存的數據,而不是再次調用服務器。這是該服務的一個示例,您如何建議使用Angular2和Typescript實現此緩存層。import {Inject, Injectable} from 'angular2/core';import {Http, Headers} from "angular2/http";import {JsonHeaders} from "./BaseHeaders";import {ProfileDetails} from "../models/profileDetails";@Injectable()export class ProfileService{    myProfileDetails: ProfileDetails = null;    constructor(private http:Http) {    }    getUserProfile(userId:number) {        return this.http.get('/users/' + userId + '/profile/', {                headers: headers            })            .map(response =>  {                if(response.status==400) {                    return "FAILURE";                } else if(response.status == 200) {                    this.myProfileDetails = new ProfileDetails(response.json());                    return this.myProfileDetails;                }            });    }}
查看完整描述

3 回答

?
翻過高山走不出你

TA貢獻1875條經驗 獲得超3個贊

關于您的最后一條評論,這是我想到的最簡單的方法:創建一個具有一個屬性并且該屬性將保存請求的服務。


class Service {

  _data;

  get data() {

    return this._data;

  }

  set data(value) {

    this._data = value;

  }

}

就如此容易。plnkr中的其他所有內容都將保持不變。我從服務中刪除了請求,因為它會自動實例化(我們不這樣做new Service...,而且我不知道通過構造函數傳遞參數的簡單方法)。


所以,現在,我們有了Service,我們現在要做的是在組件中發出請求并將其分配給Service變量 data


class App {

  constructor(http: Http, svc: Service) {


    // Some dynamic id

    let someDynamicId = 2;


    // Use the dynamic id in the request

    svc.data = http.get('http://someUrl/someId/'+someDynamicId).share();


    // Subscribe to the result

    svc.data.subscribe((result) => {

      /* Do something with the result */

    });

  }

}

請記住,我們的Service實例對于每個組件都是相同的,因此,當我們為其分配值時data,它將反映在每個組件中。

查看完整回答
反對 回復 2019-12-25
  • 3 回答
  • 0 關注
  • 1262 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號