John David

John David

1567218914

RxJS Caching and Refreshing in Angular

Originally published by Preston Lamb at https://www.prestonlamb.com         

I use Observables and RxJS every day when developing in Angular, but many times I just use the default, out-of-the-box, standard features. But what I really wanted for a recent project was to cache some of the data that we needed to get from the server. The data doesn’t change frequently, so caching the response for an hour or two before re-fetching the data was perfect. Luckily, RxJS has the shareReplay operator, which automatically shares previous responses with new subscribers. In many cases, that’s a sufficient way to cache the data. But if you want to update the data after a certain time period, you need a combination of shareReplay, defer, and mergeMap so that when a subscriber is added to an observable, the data is refreshed if necessary. Check out the examples below, and read on for more information.

Caching Data with RxJS

The other day I was working on an application at work where we needed to get some data from the server, but the data doesn’t update very frequently. So getting the information once an hour or so is no issue. RxJS makes this really easy to do! I was in luck! Here’s all you need to do to to have RxJS cache data and provide that same data to other subscribers:

this._http.get(this.url).pipe(shareReplay(1));

This example uses Angular’s HttpClient module to make a call to an API endpoint at some url, and uses the shareReplay operator to tell RxJS to send the latest data to new subscribers. You can read more about shareReplayin the RxJS docs. The 1 that is passed in to the shareReplay operator here sets the buffer size of the operator to 1, which is why it shares only the latest data with new subscribers.

In many cases, this caching method is sufficient. The data will be updated when the application is refreshed. As long as the data doesn’t need to be refreshed before then, this works perfectly. However, if you can’t wait until the app is refreshed for the data to be refreshed, we’ll need to do a little more.

Caching and Updating Data with RxJS

Okay, so now let’s pretend we want to cache our data for 5 minutes, and after 5 minutes we need to get it updated for the next subscriber. Luckily, shareReplay can take a second parameter, windowTime. windowTime essentially declares how long the data will be cached with shareReplay. So, if we passed in 5 minutes as the windowTime, then any subscribers from the first one at 0 seconds to a subscriber at 4 minutes and 59 seconds will get the same data. At 5 minutes, the observable completes and any subscribers after will just get a null value back.

Now, that’s not exactly what we want, because new subscribers after the windowTime have no data, but we really want them to have data (obviously). So this is the question that Ben Lesh answered on Twitter for me. Here’s his tweet:

Hmm.. that's tricky. RxJS doesn't have anything like that OOTB, but the first thing that pops into my mind would be something like this: pic.twitter.com/YnJWaLZMx4
— Ben Lesh (@BenLesh) August 28, 2019

You can read the comments in the code for his picture as well, but the createShared function initializes the shared$ observable with the data$ observable. It also uses defer, which is used if null is the first value emitted from the shared$ observable. In that case, it creates a new instance of the observable and passes that along. I tested this out, and it worked perfectly. Take a look at this StackBlitz example. The observable is subscribed to as soon as the component loads, and then after the windowTime expires a second subscriber jumps in and gets new data. There’s a good chance that the two sets of data will not be matched up, since the first observable completed. (* Note: the item that shows is randomly chosen from 1 to 10 from the list of people returned from the Star Wars API. There’s a chance that the same number comes up twice, but the first one didn’t update its data to match a new, second call for data.)

To make it easier to create this type of observable, I created this function:

let returnObs$: Observable<any>;

const createReturnObs = (obs: Observable<any>, time: number, bufferReplays: number) =>

        (returnObs$ = obs.pipe(shareReplay(bufferReplays, time)));

 

export function renewAfterTimer(obs: Observable<any>, time: number, bufferReplays: number = 1) {

        return createReturnObs(obs, time, bufferReplays).pipe(

               first(null, defer(() => createReturnObs(obs, time, bufferReplays))),

               mergeMap(d => (isObservable(d) ? d : of(d))),

        );

}

 To get a new observable that will cache data for a given amount of time, and then be refreshed for new subscribers after the given time, use that function like this:

myObs$ = renewAfterTimer(of(true), 1500);

where of(true) is the observable you need to be refreshed.

Conclusion

So, as a review, use the shareReplay operator from RxJS to cache data for your application. Use the above example from Ben (or the function I built to create those observables that Ben mentioned) to create an observable that caches the data for a certain amount of time and then refreshes for new subscribers.

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

Angular 8 (formerly Angular 2) - The Complete Guide

Angular & NodeJS - The MEAN Stack Guide

The Complete Node.js Developer Course (3rd Edition)

The Web Developer Bootcamp

Best 50 Angular Interview Questions for Frontend Developers in 2019

How to build a CRUD Web App with Angular 8.0

React vs Angular: An In-depth Comparison

React vs Angular vs Vue.js by Example

#angular

What is GEEK

Buddha Community

RxJS Caching and Refreshing in Angular
Christa  Stehr

Christa Stehr

1598940617

Install Angular - Angular Environment Setup Process

Angular is a TypeScript based framework that works in synchronization with HTML, CSS, and JavaScript. To work with angular, domain knowledge of these 3 is required.

  1. Installing Node.js and npm
  2. Installing Angular CLI
  3. Creating workspace
  4. Deploying your First App

In this article, you will get to know about the Angular Environment setup process. After reading this article, you will be able to install, setup, create, and launch your own application in Angular. So let’s start!!!

Angular environment setup

Install Angular in Easy Steps

For Installing Angular on your Machine, there are 2 prerequisites:

  • Node.js
  • npm Package Manager
Node.js

First you need to have Node.js installed as Angular require current, active LTS or maintenance LTS version of Node.js

Download and Install Node.js version suitable for your machine’s operating system.

Npm Package Manager

Angular, Angular CLI and Angular applications are dependent on npm packages. By installing Node.js, you have automatically installed the npm Package manager which will be the base for installing angular in your system. To check the presence of npm client and Angular version check of npm client, run this command:

  1. npm -v

Installing Angular CLI

  • Open Terminal/Command Prompt
  • To install Angular CLI, run the below command:
  1. npm install -g @angular/cli

installing angular CLI

· After executing the command, Angular CLI will get installed within some time. You can check it using the following command

  1. ng --version

Workspace Creation

Now as your Angular CLI is installed, you need to create a workspace to work upon your application. Methods for it are:

  • Using CLI
  • Using Visual Studio Code
1. Using CLI

To create a workspace:

  • Navigate to the desired directory where you want to create your workspace using cd command in the Terminal/Command prompt
  • Then in the directory write this command on your terminal and provide the name of the app which you want to create. In my case I have mentioned DataFlair:
  1. Ng new YourAppName

create angular workspace

  • After running this command, it will prompt you to select from various options about the CSS and other functionalities.

angular CSS options

  • To leave everything to default, simply press the Enter or the Return key.

angular setup

#angular tutorials #angular cli install #angular environment setup #angular version check #download angular #install angular #install angular cli

Sasha  Roberts

Sasha Roberts

1626834660

Angular Rxjs: Use .map() And Async Pipe (Refactor Your Code)

In this video, we will see how to improve our code using the #rxs map operator and #angular #async pipe.

The components should be clean and minimal and should not have code that manipulates the data. Responsible for data manipulation is a service.
The goal is to prepare our data and return an #observable pipe so that we can use an #async pipe in the template.

code: https://github.com/profanis/codeShotsWithProfanis/tree/13/rxjsMapAndAsyncPipe

#angular #rxjs #observable #map #async

#angular rxjs #angular #angular tutorial #what is angular

Roberta  Ward

Roberta Ward

1593184320

Basics of Angular: Part-1

What is Angular? What it does? How we implement it in a project? So, here are some basics of angular to let you learn more about angular.

Angular is a Typescript-based open-source front-end web application platform. The Angular Team at Google and a community of individuals and corporations lead it. Angular lets you extend HTML’s syntax to express your apps’ components clearly. The angular resolves challenges while developing a single page and cross-platform applications. So, here the meaning of the single-page applications in angular is that the index.html file serves the app. And, the index.html file links other files to it.

We build angular applications with basic concepts which are NgModules. It provides a compilation context for components. At the beginning of an angular project, the command-line interface provides a built-in component which is the root component. But, NgModule can add a number of additional components. These can be created through a template or loaded from a router. This is what a compilation context about.

What is a Component in Angular?

Components are key features in Angular. It controls a patch of the screen called a view. A couple of components that we create on our own helps to build a whole application. In the end, the root component or the app component holds our entire application. The component has its business logic that it does to support the view inside the class. The class interacts with the view through an API of properties and methods. All the components added by us in the application are not linked to the index.html. But, they link to the app.component.html through the selectors. A component can be a component and not only a typescript class by adding a decorator @Component. Then, for further access, a class can import it. The decorator contains some metadata like selector, template, and style. Here’s an example of how a component decorator looks like:

@Component({
    selector: 'app-root',
    templateUrl: 'app.component.html',
    styleUrls: ['app.component.scss']
})

Role of App Module

Modules are the package of functionalities of our app. It gives Angular the information about which features does my app has and what feature it uses. It is an empty Typescript class, but we transform it by adding a decorator @NgModule. So, we have four properties that we set up on the object pass to @NgModule. The four properties are declarations, imports, providers, and bootstrap. All the built-in new components add up to the declarations array in @NgModule.

@NgModule({
declarations: [
  AppComponent,
],
imports: [
  BrowserModule,
  HttpClientModule,
  AppRoutingModule,
  FormsModule
],
bootstrap: [AppComponent]
})

What is Data Binding?

Data Binding is the communication between the Typescript code of the component and the template. So, we have different kinds of data binding given below:

  • When there is a requirement to output data from our Typescript code in the HTML template. String interpolation handles this purpose like {{data}} in HTML file. Property Binding is also used for this purpose like [property] = “data”.
  • When we want to trigger any event like clicking a button. Event Binding works while we react to user events like (event) = “expression”.
  • When we can react to user events and output something at the same time. Two-way Binding is used like [(ngModel)] = “data”.

image for understanding data binding

#angular #javascript #tech blogs #user interface (ui) #angular #angular fundamentals #angular tutorial #basics of angular

Flexible Caching and Refreshing with RxJS in Angular

Caching data in RxJS is a handy feature that can increase the responsiveness of your site (or at least it will feel that way to your users). And on some devices and in some scenarios, saving that extra HTTP call is really important. So when data doesn’t change frequently it makes a lot of sense to cache the data that came back and share it in multiple places, or when the user leaves the route and goes back to the same page. To read more about my current favorite way of doing this, read my last article on caching and refreshing data using RxJS here. In that article, you’ll learn how to create an observable that will share the HTTP call data with new subscribers, but after a user defined amount of time, the call will be re-made so that the data is fresh. Here’s what that looks like though, as a refresher for those that have already read that article:

let returnObs$: Observable<any>;

const createReturnObs = (obs: Observable<any>, time: number, bufferReplays: number) =>
	(returnObs$ = obs.pipe(shareReplay(bufferReplays, time)));

export function renewAfterTimer(obs: Observable<any>, time: number, bufferReplays: number = 1) {
	return createReturnObs(obs, time, bufferReplays).pipe(
		first(null, defer(() => createReturnObs(obs, time, bufferReplays))),
		mergeMap(d => (isObservable(d) ? d : of(d))),
	);
}

This function creates an observable that caches the data for the user defined amount of time, and then if a new subscriber comes after it “expires”, the HTTP call is made again and the cached data is replaced.

That function works great, and the new function that I’m going to show you today uses the above, but adds a little bit more flexibility.

Flexibility in Caching Data

The above function is great for data that doesn’t require parameters, like a list of items or something like that. It’s perfect in that case because you can just create the observable and know that every time someone asks for that data it will be the same. But what if you want to get the details of an item and cache it?

In my case, we have some data that needs to be loaded for the current month. Most of the time, they’ll only want the current month, so we want to cache the response. But every now and then they’ll go back to a previous month to view that data. In that case, we want to replace the cache with our new data. What I didn’t want to do, though, was have a big list of observables that I was trying to keep track of, creating a new one each time the function was called. That’s fine, and might work, but I wanted a single observable in my service that was passed around.

Here’s how I did this:

export class SwapiService {
	constructor(private _http: HttpClient) {}

	private lastCharacterQueried: string;
	private steps$: Observable<any>;

	getCharacter(characterId: string) {
		if (characterId !== this.lastCharacterQueried) {
			this.steps$ = renewAfterTimer(this._http.get(`https://swapi.co/api/people/${characterId}`), 10 * 1000);
			this.lastCharacterQueried = characterId;
		}
		return this.steps$;
	}
}

In this example, I’m using the Star Wars API (swapi.co) to get the details of a single character. To do that, I call the getCharacter function and pass an ID into the function. I check to see if the ID is the same as the last one that was passed in. If so, I just return the observable I already created. If now, I create a new observable that will renew after 10 seconds, then save the character ID and return the observable.

#angular #rxjs #programming

Ayyaz Zafar

1624138795

Angular Material Autocomplete - Multiple Use Cases covered

Learn How to use Angular Material Autocomplete Suggestions Search Input. I covered multiple use cases.

Please watch this video. I hope this video would be helpful for you to understand it and use it in your projects

Please subscribe: https://www.youtube.com/channel/UCL5nKCmpReJZZMe9_bYR89w

#angular #angular-material #angular-js #autocomplete #angular-material-autocomplete #angular-tutorial