Home Web Front-end JS Tutorial An Angular method-level cache annotation (decorator)

An Angular method-level cache annotation (decorator)

May 30, 2018 pm 05:30 PM
angular annotation cache

This article mainly introduces a kind of angular method-level cache annotation (decorator). Now I share it with you and give it as a reference.

You can do a lot of things using decorators in es6. Today I will share a function of using decorators to cache method calls in angular.

The application scenario is like this. In front-end work, there are some frequently used methods that are often called, but each call of these methods takes up a lot of resources, such as network requests, data statistics functions, etc. Generally, the results returned will be different depending on the parameters passed in the function call.

Because I have used the cache function in spring, I feel that it would be great if there were spring cacheable annotations in es. The annotations in spring are used as follows:

@Cacheable(value="'accountCache_'+#userName")// 缓存名叫 accountCache_USERNAME  
public Account getAccountByName(String userName) {  
// @@@@
return acount;  
}
Copy after login

The cache time in spring is configured in the configuration file, but on the front end we generally need to set different cache times for different functions
So we need to specify the corresponding cache time each time

@cacheable(111)
getSecondLeftMenu(topMenuId: number){
return 1111;
}
Copy after login

So I made a cache annotation that supports returning Promise objects

export function cacheable(timeout:number) {
  return function (target: any, key: string, descriptor: any) {
     const originalMethod = descriptor.value;
     descriptor.value = function (...args: any[]) {
//把传入的参数和被调的函数名一起组成存储的主键
       const paramStr = args.map(a => JSON.stringify(a)).join();
       const keyStr=key+"start$$"+(paramStr||"")+"-$$end";
       let resultStr=localStorage.getItem(keyStr);
       if (!!resultStr) {
         let resultValue=JSON.parse(resultStr);
          let now=new Date() as any;
//把缓存时的时间和当前的时间进行对比,如果没有超时,则直接返回
          let old2=(new Date(resultValue.date)) as any;
          let delt=now - old2;
          if (delt<(timeout*1000)) {
            return Promise.resolve(resultValue.value);
          }
       }
//超时时,调用原方法,并记录返回结果,这里我们的返回均是promise对象
       var result = originalMethod.apply(this, args);
       result.then(data=>{
        let dd={
          date:new Date(),
          value:data
        }
        localStorage.setItem(keyStr,JSON.stringify(dd))
        return Promise.resolve(data);
       },data=>{
        return Promise.reject(data);
       })
       return result;
     }
     return descriptor;
    }
}
Copy after login

The above is what I compiled for everyone Yes, I hope it will be helpful to everyone in the future.

Related articles:

How to introduce the icon icon into the Vue project

E-mail address format verification in JavaScript

Introduction to time-sharing functions for javascript performance optimization

##

The above is the detailed content of An Angular method-level cache annotation (decorator). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Where are video files stored in browser cache? Where are video files stored in browser cache? Feb 19, 2024 pm 05:09 PM

Which folder does the browser cache the video in? When we use the Internet browser every day, we often watch various online videos, such as watching music videos on YouTube or watching movies on Netflix. These videos will be cached by the browser during the loading process so that they can be loaded quickly when played again in the future. So the question is, in which folder are these cached videos actually stored? Different browsers store cached video folders in different locations. Below we will introduce several common browsers and their

How to install Angular on Ubuntu 24.04 How to install Angular on Ubuntu 24.04 Mar 23, 2024 pm 12:20 PM

Angular.js is a freely accessible JavaScript platform for creating dynamic applications. It allows you to express various aspects of your application quickly and clearly by extending the syntax of HTML as a template language. Angular.js provides a range of tools to help you write, update and test your code. Additionally, it provides many features such as routing and form management. This guide will discuss how to install Angular on Ubuntu24. First, you need to install Node.js. Node.js is a JavaScript running environment based on the ChromeV8 engine that allows you to run JavaScript code on the server side. To be in Ub

How to view and refresh dns cache in Linux How to view and refresh dns cache in Linux Mar 07, 2024 am 08:43 AM

DNS (DomainNameSystem) is a system used on the Internet to convert domain names into corresponding IP addresses. In Linux systems, DNS caching is a mechanism that stores the mapping relationship between domain names and IP addresses locally, which can increase the speed of domain name resolution and reduce the burden on the DNS server. DNS caching allows the system to quickly retrieve the IP address when subsequently accessing the same domain name without having to issue a query request to the DNS server each time, thereby improving network performance and efficiency. This article will discuss with you how to view and refresh the DNS cache on Linux, as well as related details and sample code. Importance of DNS Caching In Linux systems, DNS caching plays a key role. its existence

How are annotations used for test methods in the JUnit framework? How are annotations used for test methods in the JUnit framework? May 06, 2024 pm 05:33 PM

Annotations in the JUnit framework are used to declare and configure test methods. The main annotations include: @Test (declaration of test methods), @Before (method run before the test method is executed), @After (method run after the test method is executed), @ BeforeClass (method that runs before all test methods are executed), @AfterClass (method that runs after all test methods are executed), these annotations help organize and simplify the test code, and improve the reliability of the test code by providing clear intentions and configurations. Readability and maintainability.

The King of PHP Code Documentation: An Advanced Guide to PHPDoc The King of PHP Code Documentation: An Advanced Guide to PHPDoc Mar 02, 2024 am 08:43 AM

Introduction: PHPDoc is a comment standard for PHP code that produces easy-to-understand and informative documentation. By using specific comment tags, PHPDoc allows developers to provide important details about functions, classes, methods, and other code elements. This advanced guide takes an in-depth look at PHPDoc, demonstrating its capabilities and providing effective documentation strategies. Syntax and tags: PHPDoc comments start with double slashes (//) or multi-line comments (/**/). Here are some common annotation tags: @param: Defines the parameters of a function or method. @return: Specifies the return value of the function or method. @throws: Describes exceptions that may be thrown by a function or method. @var: defines the attributes or instances of the class

How do annotations in the Jackson library control JSON serialization and deserialization? How do annotations in the Jackson library control JSON serialization and deserialization? May 06, 2024 pm 10:09 PM

Annotations in the Jackson library control JSON serialization and deserialization: Serialization: @JsonIgnore: Ignore the property @JsonProperty: Specify the name @JsonGetter: Use the get method @JsonSetter: Use the set method Deserialization: @JsonIgnoreProperties: Ignore the property @ JsonProperty: Specify name @JsonCreator: Use constructor @JsonDeserialize: Custom logic

Angular components and their display properties: understanding non-block default values Angular components and their display properties: understanding non-block default values Mar 15, 2024 pm 04:51 PM

The default display behavior for components in the Angular framework is not for block-level elements. This design choice promotes encapsulation of component styles and encourages developers to consciously define how each component is displayed. By explicitly setting the CSS property display, the display of Angular components can be fully controlled to achieve the desired layout and responsiveness.

Will HTML files be cached? Will HTML files be cached? Feb 19, 2024 pm 01:51 PM

Title: Caching mechanism and code examples of HTML files Introduction: When writing web pages, we often encounter browser cache problems. This article will introduce the caching mechanism of HTML files in detail and provide some specific code examples to help readers better understand and apply this mechanism. 1. Browser caching principle In the browser, whenever a web page is accessed, the browser will first check whether there is a copy of the web page in the cache. If there is, the web page content is obtained directly from the cache. This is the basic principle of browser caching. Benefits of browser caching mechanism

See all articles