Skip to content

Instantly share code, notes, and snippets.

@arutnik
Created July 8, 2018 19:46
Show Gist options
  • Select an option

  • Save arutnik/dd6cd06a5edf04c0b704b687fa37e2b1 to your computer and use it in GitHub Desktop.

Select an option

Save arutnik/dd6cd06a5edf04c0b704b687fa37e2b1 to your computer and use it in GitHub Desktop.
SEO-SPA: Pagination service
import { Injectable, Renderer2, Inject, ElementRef } from "@angular/core";
import { ActivatedRoute } from "@angular/router";
import { DOCUMENT } from "@angular/platform-browser";
//This should be injected in the app component, and any component or service
//that is responsible for pagination
@Injectable()
export class PaginationService {
private totalPages: number;
private currentPageNumber: number;
private baseUrl: string;
private prevLinkRef: ElementRef;
private nextLinkRef: ElementRef;
constructor(private renderer: Renderer2, private activatedRoute: ActivatedRoute,
@Inject(DOCUMENT) private document
) {
this.activatedRoute.url.subscribe((url) => {
this.baseUrl = '/' + url.join('/');
});
}
public updatePagination(currentPageNumber: number, totalPages: number) {
this.currentPageNumber = currentPageNumber;
this.totalPages = totalPages;
this.updateLinkTags();
}
private updateLinkTags() {
if (this.totalPages > 1) {
// We only add the next page if there is more than 1 page, and not on the last page
if (this.currentPageNumber < this.totalPages - 1) {
const linkTagNext = this.nextLinkRef ? this.nextLinkRef : this.renderer.createElement('link');
this.renderer.setAttribute(linkTagNext, 'rel', 'next');
this.renderer.setAttribute(linkTagNext, 'href', this.baseUrl + '?page=' + (this.currentPageNumber + 1));
if (!this.nextLinkRef) {
this.nextLinkRef = linkTagNext;
this.renderer.appendChild(this.document.head, linkTagNext);
}
}
else if (this.nextLinkRef) this.removeNextTag();
// We only add the prev page if there is more than 1 page, and not on the first page
if (this.currentPageNumber > 0) {
const linkTagPrev = this.prevLinkRef ? this.prevLinkRef : this.renderer.createElement('link');
this.renderer.setAttribute(linkTagPrev, 'rel', 'prev');
this.renderer.setAttribute(linkTagPrev, 'href', this.baseUrl + '?page=' + (this.currentPageNumber - 1));
if (!this.prevLinkRef) {
this.prevLinkRef = linkTagPrev;
this.renderer.appendChild(this.document.head, linkTagPrev);
}
}
else if (this.prevLinkRef) {
this.removePrevTag();
}
}
else {
this.removeLinkTags();
}
}
private removeLinkTags() {
if (this.prevLinkRef) this.removePrevTag();
if (this.nextLinkRef) this.removeNextTag();
}
private removeNextTag() {
this.renderer.removeChild(this.document.head, this.nextLinkRef);
this.nextLinkRef = null;
}
private removePrevTag() {
this.renderer.removeChild(this.document.head, this.prevLinkRef);
this.prevLinkRef = null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment