1 view

Wrapping third party service in Angular

Step 1: npm install toastr –save

Step 2: import angular.json file toastr.min.css in styles and toastr.min.js in scripts

 "styles": [
              "node_modules/toastr/build/toastr.min.css",
              "node_modules/bootstrap/dist/css/bootstrap.min.css",
              "src/styles.css"
            ],
"scripts": [
              "node_modules/jquery/dist/jquery.min.js",
              "node_modules/toastr/build/toastr.min.js",              
              "node_modules/bootstrap/dist/js/bootstrap.js"
            ]

Step 3: Add a click event before that create a common service (step 4)

import { EventService } from './shared/event.service';
import { Component, OnInit } from '@angular/core';
import { ToastrService } from '../common/toastr.service';

@Component({
    selector: "events-list",
    template: `
    <div>
    <h2>Upcoming Angular Evnets</h2>
        <hr>
        <div class="row">
            <div class="col-md-5" *ngFor="let event of events">
                <event-thumbnail (click)="handleThumbnailClick(event.name)"  [event]="event"></event-thumbnail>
            </div>
        </div>
    </div>
    `
})


export class EventListComponent implements OnInit{

    events: any[];

    constructor(private eventService: EventService, private toastr: ToastrService){
        
    }

    ngOnInit(){
        this.events = this.eventService.getEvents();
    }
    handleThumbnailClick(eventName){
        this.toastr.success(eventName);
    }

}

Step 4: create a service file toastr.service.ts into app/common folder

import { Injectable } from '@angular/core';

declare let toastr:any;

@Injectable()
export class ToastrService{

    success(message: string, title?: string){
        toastr.success(message, title);
    }
    info(message: string, title?: string){
        toastr.info(message, title);
    }
    warning(message: string, title?: string){
        toastr.warning(message, title);
    }
    error(message: string, title?: string){
        toastr.error(message, title);
    }

}

Leave a Reply