4

I am using ngx-toastr in angular 6 for http error notification, as injected ToastrService in httpInterceptor

    export class MyInterceptor implements HttpInterceptor {
        constructor(public toasterService: ToastrService) { }

        intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
            return next.handle(request)
                .pipe(
                    tap((evt: any) => {
                        if (evt instanceof HttpResponse) {
                            if (evt.body)
                                this.toasterService.success('success', '!!', { positionClass: 'toast-bottom-center' });
                                //alert(`success`);

                        }
                    }),
                    catchError((err: any) => {                    
                        if (err instanceof HttpErrorResponse) {
                            try {
                                this.toasterService.error(err.error.message, err.error.title, { positionClass: 'toast-bottom-center' });

                            } catch (e) {
                                this.toasterService.error('An error occurred', '', { positionClass: 'toast-bottom-center' });

                            }
                            //log error 
                        }
                        return of(err);
 })
            )
    }
}

and imported ToastrModule in app.module.ts like

imports:[
ToastrModule.forRoot()
]

I am getting below error, any idea whats going wrong here..............

ngx-toastr.js?4996:264 Uncaught TypeError: Object(...) is not a function at eval (ngx-toastr.js?4996:264) .................................

1 Answers1

2

I found the actual issue regarding this. It's happening because of the mismatch of the version of an angular and the package. To overcome this problem perform the following steps

STEP1: Check for angular CLI version: ng --version

Now check this image

enter image description here

If your angular version is 7.3.10 then you need to install 10.1.0 version of ngx-toastr

enter image description here

STEP2: Install a specific version of ngx-toastr according to your angular CLI version: npm i ngx-toastr@10.1.0 --save

STEP3: import it into app.module.ts

app.module.ts

import { CommonModule } from '@angular/common';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
 
import { ToastrModule } from 'ngx-toastr';
 
@NgModule({
  imports: [
    CommonModule,
    BrowserAnimationsModule, // required animations module
    ToastrModule.forRoot() // ToastrModule added
  ],
  bootstrap: [App],
  declarations: [App]
})

export class AppModule {}

STEP4: add css path in styles array in angular.json file

angular.json

"styles": [
    "node_modules/font-awesome/css/font-awesome.css",
    "src/styles/app.scss",
    "node_modules/sweetalert2/dist/sweetalert2.min.css",
    "node_modules/ngx-toastr/toastr.css"
]

Don't forget to restart your server after making changes in angular.json file

STEP5: make helper service to show toasters

helper.service.ts

import { Injectable } from '@angular/core';
import { ToastrService } from 'ngx-toastr';

@Injectable({
    providedIn: 'root'
})

export class HelperService {
    constructor(private toastr: ToastrService) { };

    showSuccessToast(msg) {
        this.toastr.success(msg);
    }

    showErrorToast(msg) {
        this.toastr.error(msg);
    }

    showInfoToast(msg) {
        this.toastr.info(msg);
    }
}

STEP6: Now you are done you just need to use these functions in your component.ts file

user.component.ts

import { Component, OnInit } from '@angular/core';
import { routerTransition } from '../../router.animations';
import { UserService } from './user.service';
import { HelperService } from 'src/app/helpers/helper.service';

@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.scss'],
  animations: [routerTransition()]
})

export class UserComponent implements OnInit {

  constructor(
    private userService: UserService,
    private helperService: HelperService,
  ) {
  }

  ngOnInit() {
    this.getUsers();
  }

  async getUsers() {
    try {
      const res: any = await this.userService.getUsers();
      this.helperService.showSuccessToast(res.message);
    } catch (err) {
      this.helperService.showErrorToast(err.error || 'Something went wrong');
    }
  }

}
Neel Rathod
  • 2,013
  • 12
  • 28
  • As per the [docs](https://www.npmjs.com/package/ngx-toastr#setup), only add the css to the json file if you're on Angular < 6, otherwise add the following to your style.css `@import '~ngx-toastr/toastr';` – Mendy Sep 10 '20 at 17:37
  • Refer to the official docs for the latest dependencies. The image attached above has changed since. – async_soul Dec 07 '21 at 05:36