In this chapter, we will see how to use RxJs with Angular. We will not get into the installation process for Angular here, to know about Angular Installation refer this link −https://www.tutorialspoint.com/angular7/angular7_environment_setup.htm
We will directly work on an example, where will use Ajax from RxJS to load data.
Example
app.component.ts
import { Component } from '@angular/core';
import { environment } from './../environments/environment';
import { ajax } from 'rxjs/ajax';
import { map } from 'rxjs/operators'
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = '';
data;
constructor() {
this.data = "";
this.title = "Using RxJs with Angular";
let a = this.getData();
}
getData() {
const response =
ajax('https://jsonplaceholder.typicode.com/users')
.pipe(map(e => e.response));
response.subscribe(res => {
console.log(res);
this.data = res;
});
}
}
app.component.html
<div>
<h3>{{title}}</h3>
<ul *ngFor="let i of data">
<li>{{i.id}}: {{i.name}}</li>
</ul>
</div>
<router-outlet></router-outlet>
We have used ajax from RxJS that will load data from this url − https://jsonplaceholder.typicode.com/users.
When you compile the display is as shown below −
Leave a Reply