在外部模块中使用配置类

时间:2018-01-25 11:47:43

标签: angular typescript

我正在开发一个使用一些外部模块的角度应用程序。

我的最终应用程序包含一些配置类,这些配置类包含URL的值,与服务器交换的消息键,等等。

作为一个例子,让我们说我的最终申请中定义了以下类:

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

@Injectable()
export class Messages {
    private static _instance: Messages;

    public static readonly ERROR_HTTP_INTERNAL: string = "error.http.internal";
    public static readonly ERROR_HTTP_UNAUTHORIZED: string = "error.http.unauthorized";
    public static readonly ERROR_HTTP_FORBIDDEN: string = "error.http.forbidden";

    constructor() {

    }
}

我想在外部模块中使用此类,以便在出现http错误时显示错误消息:

@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {

  constructor(private snackBar: MatSnackBar) {
  }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).do((event: HttpEvent<any>) => {
      if (event instanceof HttpResponse) {
        // Do stuff with response
      }
    }, (errorResponse: any) => {
      if (errorResponse instanceof HttpErrorResponse) {
        let errorKey: string = errorResponse.error;
        if (!errorKey) {
          switch (errorResponse.status) {
            case 401:
              errorKey = Messages.ERROR_HTTP_UNAUTHORIZED;
              break;
            case 403:
              errorKey = Messages.ERROR_HTTP_FORBIDDEN;
              break;
            default:
              errorKey = Messages.ERROR_HTTP_INTERNAL;
              break;
          }

          //Manage the display of the error message
        }

        //Manage the display of the error message
      }
    });
  }
}

我的问题是:

  1. 如何将我的最终应用程序的Messages类导出到我的外部模块的HttpErrorInterceptor类?
  2. 这个模块分离是一个好方法吗?如果HttpErrorInterceptor保留在最终应用程序中或在外部模块中以更简单的方式定义它会不会更好?

1 个答案:

答案 0 :(得分:0)

您可以将消息存储在json文件中,并在应用程序使用 MessageService 启动时读取它。然后,您可以在任何需要的地方注入此服务:

您的MessageService:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { HttpClient } from '@angular/common/http';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class MessageService {

  public messages: any;

  constructor(private http: HttpClient) { }

  loadMessages(): Promise<any> {
    return this.http.get('./../../../assets/messages.json')
      .toPromise()
      .then((data: any) => {
        this.config = data;
      })
      .catch((err: any) => {
        Promise.resolve();
      });
  }
}

你的app.module.ts:

import { MessageService } from './services/messages/message.service';

export function messageServiceFactory(messageService: MessageService): Function {
  return () => messageService.loadMessages();
}

@NgModule({
  declarations: [
  // ...
  ]

providers: [

    MessageService,
    {
      // Provider for APP_INITIALIZER
      provide: APP_INITIALIZER,
      useFactory: messageServiceFactory,
      deps: [MessageService],
      multi: true,
    },
    //...

    ],
  bootstrap: [AppComponent]
})
export class AppModule { }

并像其他地方一样使用它:

@Injectable()
export class AnotherService {
constructor(private messageService: MessageService) {}

doStuff() {
    console.log('ERROR_HTTP_UNAUTHORIZED', 
    this.messageService.messages.ERROR_HTTP_UNAUTHORIZED);
    }
}