Angular之ng-alain项目实战(二)项目改造

创建好的项目会有一些初始化的设置,现在要根据业务需求和后端对接时的一些个性化需求进行部分修改和设置
1.在shared目录下创建一个ts文件,用来设置一些常量
例:app-constants.ts

/**
 * 本地存储
 */
export const STORAGE = {};

/**
 * 正则校验
 */
export const REG_EXP_IDENTITY: RegExp = /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
/**
 * 本地缓存
 */
export const CACHE = {};
/**
 * 请求设置
 */
export const OPTIONS: any = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
  observe: 'response',
  responseType: 'json',
  withCredentials: true,
};
/**
 * API
 */
export const API = {
  /**登入*/
  USER_LOGIN: '/****/login?_allow_anonymous=true',
  /**登出*/
  USER_LOGOUT: '/****/logout',
};

2.在shared目录下创建一个文件夹 components ,用来存放一些常用的组件

3.delon.module.ts中,在fnDelonAuthConfig 方法中设置发送token参数名,默认:token

import { DelonAuthConfig } from '@delon/auth';
export function fnDelonAuthConfig(): DelonAuthConfig {
  return {
    ...new DelonAuthConfig(),
    login_url: '/passport/login',
    token_send_key: '****-token',
  };
}

4.在code目录中创建services文件夹,用来存放个业务模块需要的与后端交互的service文件
5.在code目录中创建 common 文件夹,存放公用的代码
例如:
(1)全局缓存

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

import * as _ from 'lodash';

@Injectable({
  providedIn: 'root',
})
/**
 * 全局缓存
 */
export class AppGlobalCacheService {
  _cache: any = {};

  constructor() {}

  get cache() {
    return (this._cache = this.clone(this._cache));
  }

  set cache(value) {
    throw new Error('do not mutate the `.cache` directly');
  }

  get(prop: string | string[], key?: string) {
    const cache = this.cache;
    return _.get(cache, prop, null);
  }

  set(prop: string | string[], value: any) {
    _.set(this._cache, prop, value);
  }

  has(prop: string): boolean {
    return !_.isNull(this.get(prop));
  }

  clean() {
    this._cache = {};
  }

  private clone(object) {
    return JSON.parse(JSON.stringify(object));
  }
}

(2)路由守卫

import { Inject, Injectable, Injector } from '@angular/core';
import { CanActivate, CanActivateChild, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs';
import { DA_SERVICE_TOKEN, ITokenService } from '@delon/auth';

@Injectable({
  providedIn: 'root',
})
/**
 * 路由守卫
 */
export class AppGuardService implements CanActivate, CanActivateChild {
  constructor(private injector: Injector, @Inject(DA_SERVICE_TOKEN) private tokenService: ITokenService) {}

  /**控制是否允许进入路由。 */
  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot,
  ): boolean | Observable<boolean> | Promise<boolean> {
    return this.logined();
  }

  /**等同 canActivate,只不过针对是所有子路由。 */
  canActivateChild(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot,
  ): boolean | Observable<boolean> | Promise<boolean> {
    return this.logined();
  }

  private logined(): boolean {
    const tokenData = this.tokenService.get();
    if (!tokenData.token) {
      this.injector.get(Router).navigateByUrl('/passport/login');
      return false;
    }
    return true;
  }
}

(3)本地储存

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

@Injectable({
  providedIn: 'root',
})
/**本地储存 */
export class AppStorageService {
  constructor() {}

  write(key: string, value: any): void {
    if (value) {
      value = JSON.stringify(value);
    }
    localStorage.setItem(key, value);
  }

  read<T>(key: string): T {
    const value: string = localStorage.getItem(key);

    if (value && value !== 'undefined' && value !== 'null') {
      return <T>JSON.parse(value);
    }

    return null;
  }

  remove<T>(key: string): void {
    const value: string = localStorage.getItem(key);

    if (value && value !== 'undefined' && value !== 'null') {
      return localStorage.removeItem(key);
    }
  }
}

6.如有需要,可在src目录下创建 models 文件夹用来存放model文件
7.environments目录下可创建多环境的配置文件
例如创建environment.uat3.ts作为测试环境的配置文件,启动和打包的时候可以选择该文件
配置angular.json文件
projects–项目名–architect–build–configurations中添加

"uat3": {
        "fileReplacements": [
            {
                "replace": "src/environments/environment.ts", 
                "with": "src/environments/environment.uat3.ts"
            }
        ], 
        "optimization": true, 
        "outputHashing": "all", 
        "sourceMap": false, 
        "extractCss": true, 
        "namedChunks": false, 
        "aot": true, 
        "extractLicenses": true, 
        "vendorChunk": false, 
        "buildOptimizer": true, 
        "budgets": [
            {
                "type": "initial", 
                "maximumWarning": "2mb", 
                "maximumError": "5mb"
            }, 
            {
                "type": "anyComponentStyle", 
                "maximumWarning": "6kb", 
                "maximumError": "10kb"
            }
        ]
}

然后在projects–项目名–architect–serve–configurations中添加

"uat3": {
  "browserTarget": "项目名:build:uat3"
},

配置package.json文件
scripts中添加

"build-uat3": "npm run color-less && node --max-old-space-size=8000 ./node_modules/@angular/cli/bin/ng build -c=uat3 --build-optimizer --outputPath=dist/uat3/comn-mng-alain",
"start-uat3": "npm run color-less && ng s -c=uat3 -o",

至此,基本的改在已完成

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值