Our NGB carousel component class

In this section, we will implement the ngb-carousel component class. The following is the updated component class. We will analyze the code in a bit:

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';

@Component({
selector: 'ngb-test-carousel',
templateUrl: './ngb-carousel.component.html',
styles: [`
.carousel {
width: 500px;
}
`]
})
export class NgbCarouselComponent implements OnInit {
images: Array<string>;

constructor(private _http: HttpClient) {}

ngOnInit() {
this._http.get('https://picsum.photos/list')
.pipe(map((images: Array<{id: number}>) => this._randomImageUrls(images)))
.subscribe(images => this.images = images);
}

private _randomImageUrls(images: Array<{id: number}>): Array<string> {
return [1, 2, 3].map(() => {
const randomId = images[Math.floor(Math.random() * images.length)].id;
return `https://picsum.photos/900/500?image=${randomId}`;
});
}
}

There are a few things going on in our component class, ngb-carousel.component.ts. We're importing the HttpClient class from Angular's http module, and we're also importing the map class from the rxjs/operators module. The HttpClient class, which we'll be looking at more closely in Chapter 11, Dependency Injection and Services, is used to fetch a JSON list of image objects from https://picsum.photos, a free service that serves up images as placeholders, providing, as their site says, The Lorem Ipsum for photos. The map class is used to randomly map three of the many image objects that are returned from the GET request of HttpClient to our string array variable, named images

The fetching of the image objects from the API happens when our component is initialized because the GET request happens within the ngOnInit() component's life cycle hook.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.51.27