import { Injectable , SecurityContext } from '@angular/core' ; import { HttpClient , HttpErrorResponse } from '@angular/common/http' ; import { throwError , Observable } from 'rxjs' ; import { map , catchError } from 'rxjs/operators' ; import { Renderer , setOptions , parse } from 'marked' ; import { DomSanitizer } from '@angular/platform-browser' ; @ Injectable ( { providedIn : 'root' , } ) export class NgxMdService { private _renderer : any = new Renderer ( ) ; constructor ( private _http , private _domSanitizer ) { this . extendRenderer ( ) ; this . setMarkedOptions ( { } ) ; } getContent ( path ) { return this . _http . get ( path , { responseType : 'text' } ) . pipe ( map ( res => this . extractData ( res ) ) , catchError ( this . handleError ) ) ; } public get renderer ( ) : Renderer { return this . _renderer ; } public extractData ( res ) { return res || '' ; } public setMarkedOptions ( options ) { options = Object . assign ( { gfm : true , tables : true , breaks : false , pedantic : false , sanitize : false , smartLists : true , smartypants : false , } , options ) ; options . renderer = this . _renderer ; setOptions ( options ) ; } public compile ( data , sanitize = true ) { return this . _domSanitizer . sanitize ( sanitize ? SecurityContext . HTML : SecurityContext . NONE , parse ( data ) . trim ( ) ) ; } private handleError ( error ) { const errMsg = error . message ? error . message : error . toString ( ) ; return throwError ( errMsg ) ; } private extendRenderer ( ) { this . _renderer . listitem = function ( text ) { if ( /^\s*\[[x ]\]\s*/ . test ( text ) ) { text = text . replace ( /^\s*\[ \]\s*/ , '<input type="checkbox" class="md-checkbox" disabled> ' ) . replace ( /^\s*\[x\]\s*/ , '<input type="checkbox" class="md-checkbox" checked disabled> ' ) ; return '<li style="list-style: none">' + text + '</li>' ; } else { return '<li>' + text + '</li>' ; } } ; } }