缓存结果与angular2 HTTP服务 [英] caching results with angular2 http service

查看:712
本文介绍了缓存结果与angular2 HTTP服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我公开通过服务的HTTP GET请求,并且若干组件正在使用该数​​据(用户简档细节)。我想,第一组分请求到实际执行的HTTP GET请求到服务器和缓存结果使随之而来的请求将使用高速缓存的数据,而不是再次呼叫服务器

下面是一个例子到服务,你会怎么推荐实施与Angular2和打字稿此缓存层。

 进口{注入,注射}从'angular2 /核心;
从angular2 / HTTP进口{HTTP,头};
从./BaseHeaders进口{JsonHeaders};
从../models/profileDetails进口{ProfileDetails};@Injectable()
出口类ProfileService {
    myProfileDetails:ProfileDetails = NULL;    构造函数(私人HTTP:HTTP){    }    getUserProfile(用户名:号){
        返回this.http.get('/用户/+用户id +'/型材/',{
                标题:标题
            })
            .MAP(响应=> {
                如果(response.status == 400){
                    返回失败;
                }否则如果(response.status == 200){
                    this.myProfileDetails =新ProfileDetails(response.json());
                    返回this.myProfileDetails;
                }
            });
    }
}


解决方案

关于你的最后一个注释,这是我能想到的最简单的方法:创建将有一个属性和属性将保持请求服务

类服务{
  _数据;
  获取数据(){
    返回this._data;
  }
  一组数据(值){
    this._data =价值;
  }
}

就这么简单。在plnkr否则一切都将是不变。我删除从服务请求,因为它会自动实例化(我们不这样做新的服务... ,我不知道一个简单的方法来传递通过构造函数的参数)。

所以,现在,我们有服务,我们现在要做的是使请求我们的组件,并将其分配给服务变量数据

类应用{
  构造函数(HTTP:HTTP,SVC:服务){    //某些动态ID
    让someDynamicId = 2;    //使用动态ID请求
    svc.data = http.get(的http:// someUrl / someId /+ someDynamicId).share();    //订阅的结果
    svc.data.subscribe((结果)=> {
      / *做一些事情的结果* /
    });
  }
}

请记住,我们的服务实例是同一个的每一个组件,所以当我们分配一个值数据将在每个组件中反映出来。

这里的 plnkr 与工作的例子。

参考

I expose an HTTP GET request through a service, and several components are using this data (profile details on a user). I would like the first component request to actually perform the HTTP GET request to the server and cache the results so the the consequent requests will use the cached data, instead of calling the server again.

Here's an example to the service, how would you recommend implementing this cache layer with Angular2 and 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;
                }
            });
    }
}

解决方案

Regarding your last comment, this is the easiest way I can think of : Create a service that will have one property and that property will hold the request.

class Service {
  _data;
  get data() {
    return this._data;
  }
  set data(value) {
    this._data = value;
  }
}

As simple as that. Everything else in the plnkr would be untouched. I removed the request from the Service because it will be instantiated automatically (we don't do new Service..., and I'm not aware of an easy way to pass a parameter through the constructor).

So, now, we have the Service, what we do now is make the request in our component and assign it to the Service variable 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 */
    });
  }
}

Remember that our Service instance is the same one for every component, so when we assign a value to data it will be reflected in every component.

Here's the plnkr with a working example.

Reference

这篇关于缓存结果与angular2 HTTP服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆