我应该将 toastr 服务放在 angular 的什么地方?
Where do I put my toastr service in angular?
我想要一个标准的 api 响应,如下所示。
成功响应:
{
"version": "1.0",
"statusCode": 200,
"result": {data....}
}
对于错误响应:
{
"version": "1.0",
"statusCode": 500, (this may be 401, 404,403,...)
"errorMessage": {message....}
}
我的服务如下:
export class MyService {
constructor(private http: HttpClient) { }
getData(): Observable<any[]> {
return this.http.get<any[]>(`http://localhost/data`).pipe(map((response: any) => {
return response;
}))
}
}
如果使用 toastr 响应有错误,我需要显示弹出窗口。那么我在哪里使用我的 toastr 服务以获得最佳解决方案?
- 组件class
- 服务class
- Http拦截器
我不想重复自己。
像这样创建服务:
declare var toastr;
@Injectable({
providedIn: 'root'
})
export class ToastrService {
displayToastr(type?: string, message?: string, autoFade?: boolean) {
var timeOut: any = "5000"
if (autoFade == false) {
timeOut = "0"
}
toastr.options = {
"closeButton": true,
"timeOut": timeOut,
}
switch (type) {
case "success":
if (message == null) {
message = "Data Saved Successfully";
}
toastr.success(message);
break;
case "error":
if (message == null) {
message = "Something Went Wrong!";
}
toastr.error(message);
break;
case "warning":
if (message == null) {
message = "Warning!";
}
toastr.warning(message);
break;
case "clear":
toastr.clear();
break;
}
}
}
然后像这样从您的组件中调用它:
constructor(private toastr: ToastrService){}
this.toastr.displayToastr("success", "User Deleted Successfully")
在你的组件constructor
中像这样调用它class
constructor(private toastr: ToastrService){}
然后在任何事件中您都可以使用
调用它
this.toastr.success("It works...");
import { ToastrService } from 'ngx-toastr';
//import your service here also
import { MyService } from './path/to/my.service'
@Component({...})
export class YourComponent {
constructor(private toastr: ToastrService,private myService:MyService) {}
getListData() {
var data = myService.getData();
if(data.statusCode==500) {
this.toastr.error(data.errorMessage, 'Major Error');
}
}
}
我建议您创建一个烤面包机服务并将该服务注入您的根拦截器。它将帮助您针对 API 的行为生成 HTTP 错误(无论状态代码是什么)。如果你想在你的组件级别自定义错误提示,你也可以使用它们,在你的组件中注入服务。
您的烤面包机服务将根据错误代码(400、403、404 等)切换案例。在您的拦截器中,只需调用带有状态代码参数的服务函数。
toaster.service.ts
httpToast(errCode){
switch(errCode){
case 400:
// your statements
break;
case 404:
// your statements
break;
}
..... // cases goes on
}
如果你有很多 http 请求,你可以通过在你的 http 拦截器 中使用它来集中化它,试试这样的事情:
@Injectable()
export class HttpInterceptor implements HttpInterceptor {
constructor(public toasterService: ToastrService) {}
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
return next.handle(req).pipe(
tap(evt => {
if (evt instanceof HttpResponse) {
if(evt.body && evt.body.success)
this.toasterService.success(evt.body.success.message, evt.body.success.title, { positionClass: 'toast-bottom-center' });
}
}),
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);
}));
}
}
我想要一个标准的 api 响应,如下所示。
成功响应:
{
"version": "1.0",
"statusCode": 200,
"result": {data....}
}
对于错误响应:
{
"version": "1.0",
"statusCode": 500, (this may be 401, 404,403,...)
"errorMessage": {message....}
}
我的服务如下:
export class MyService {
constructor(private http: HttpClient) { }
getData(): Observable<any[]> {
return this.http.get<any[]>(`http://localhost/data`).pipe(map((response: any) => {
return response;
}))
}
}
如果使用 toastr 响应有错误,我需要显示弹出窗口。那么我在哪里使用我的 toastr 服务以获得最佳解决方案?
- 组件class
- 服务class
- Http拦截器
我不想重复自己。
像这样创建服务:
declare var toastr;
@Injectable({
providedIn: 'root'
})
export class ToastrService {
displayToastr(type?: string, message?: string, autoFade?: boolean) {
var timeOut: any = "5000"
if (autoFade == false) {
timeOut = "0"
}
toastr.options = {
"closeButton": true,
"timeOut": timeOut,
}
switch (type) {
case "success":
if (message == null) {
message = "Data Saved Successfully";
}
toastr.success(message);
break;
case "error":
if (message == null) {
message = "Something Went Wrong!";
}
toastr.error(message);
break;
case "warning":
if (message == null) {
message = "Warning!";
}
toastr.warning(message);
break;
case "clear":
toastr.clear();
break;
}
}
}
然后像这样从您的组件中调用它:
constructor(private toastr: ToastrService){}
this.toastr.displayToastr("success", "User Deleted Successfully")
在你的组件constructor
中像这样调用它class
constructor(private toastr: ToastrService){}
然后在任何事件中您都可以使用
调用它this.toastr.success("It works...");
import { ToastrService } from 'ngx-toastr';
//import your service here also
import { MyService } from './path/to/my.service'
@Component({...})
export class YourComponent {
constructor(private toastr: ToastrService,private myService:MyService) {}
getListData() {
var data = myService.getData();
if(data.statusCode==500) {
this.toastr.error(data.errorMessage, 'Major Error');
}
}
}
我建议您创建一个烤面包机服务并将该服务注入您的根拦截器。它将帮助您针对 API 的行为生成 HTTP 错误(无论状态代码是什么)。如果你想在你的组件级别自定义错误提示,你也可以使用它们,在你的组件中注入服务。
您的烤面包机服务将根据错误代码(400、403、404 等)切换案例。在您的拦截器中,只需调用带有状态代码参数的服务函数。
toaster.service.ts
httpToast(errCode){
switch(errCode){
case 400:
// your statements
break;
case 404:
// your statements
break;
}
..... // cases goes on
}
如果你有很多 http 请求,你可以通过在你的 http 拦截器 中使用它来集中化它,试试这样的事情:
@Injectable()
export class HttpInterceptor implements HttpInterceptor {
constructor(public toasterService: ToastrService) {}
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
return next.handle(req).pipe(
tap(evt => {
if (evt instanceof HttpResponse) {
if(evt.body && evt.body.success)
this.toasterService.success(evt.body.success.message, evt.body.success.title, { positionClass: 'toast-bottom-center' });
}
}),
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);
}));
}
}