4

我在 Angular 6 中使用 ngx-toastr 进行 http 错误通知,就像在 httpInterceptor 中注入的 ToastrService

    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);
 })
            )
    }
}

并在 app.module.ts 中导入 ToastrModule

imports:[
ToastrModule.forRoot()
]

我遇到了错误,知道这里出了什么问题............

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

4

1 回答 1

2

我发现了关于这个的实际问题。发生这种情况是因为角度和包的版本不匹配。要克服此问题,请执行以下步骤

STEP1:检查角度 CLI 版本:ng --version

现在检查这张图片

在此处输入图像描述

如果您的 Angular 版本是7.3.10,那么您需要安装ngx-toastr的10.1.0版本

在此处输入图像描述

STEP2 :根据您的 Angular CLI 版本 安装特定版本的ngx-toastr :npm i ngx-toastr@10.1.0 --save

STEP3:导入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 : 在文件的样式数组中添加css路径angular.json

角.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"
]

angular.json更改文件后不要忘记重新启动服务器

STEP5 : 制作显示烤面包机的辅助服务

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 : 现在你已经完成了,你只需要在你的component.ts文件中使用这些函数

用户.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');
    }
  }

}
于 2020-07-03T09:11:42.640 回答