angular7.x-1项目启动

通俊发
2023-12-01
$ node -v
v8.11.2
$ npm -v
5.4.2
$ ng v

     _                      _                 ____ _     ___
    / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
   / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
  / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
 /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
                |___/


Angular CLI: 7.0.4
Node: 8.11.2
OS: win32 x64
Angular:
...

Package                      Version
------------------------------------------------------
@angular-devkit/architect    0.10.4
@angular-devkit/core         7.0.4
@angular-devkit/schematics   7.0.4
@schematics/angular          7.0.4
@schematics/update           0.10.4
rxjs                         6.3.3
typescript                   3.1.3

$ ng help

Available Commands:
add Adds support for an external library to your project.
build (b) Compiles an Angular app into an output directory named dist/ at the given output path. Must be executed from within a workspace directory.
config Retrieves or sets Angular configuration values.
doc (d) Opens the official Angular documentation (angular.io) in a browser, and searches for a given keyword.
e2e (e) Builds and serves an Angular app, then runs end-to-end tests using Protractor.
generate (g) Generates and/or modifies files based on a schematic.
help Lists available commands and their short descriptions.
lint (l) Runs linting tools on Angular app code in a given project folder.
new (n) Creates a new workspace and an initial Angular app.
run Runs a custom target defined in your project.
serve (s) Builds and serves your app, rebuilding on file changes.
test (t) Runs unit tests in a project.
update Updates your application and its dependencies. See https://update.angular.io/
version (v) Outputs Angular CLI version.
xi18n Extracts i18n messages from source code.

For more detailed help run “ng [command name] --help” 。 eg:

ng new --help    // 查看ng new的所有参数

ng new的部分参数如下:

--dry-run (-d) When true, run through and report activity without writing out results.
--prefix (-p) The prefix to apply to generated selectors.
--routing Generates a routing module.
--skip-install Skip installing dependency packages.
--style The file extension to be used for style files.
--view-encapsulation Specifies the view encapsulation strategy.

生成项目:

 ng new cloud --routing  --style scss --skip-install

装包和启动项目:

npm install
npm start

引入antd:(参考antd官网)

ng add ng-zorro-antd

引入antd前:
app.module.ts:

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

使用add的时候,可以自动在appModule中增加依赖和引用,eg:

/** 配置 angular i18n **/
import { registerLocaleData } from '@angular/common';
import zh from '@angular/common/locales/zh';
registerLocaleData(zh);

// @NgModule中:
 /** 导入 ng-zorro-antd 模块 **/
    NgZorroAntdModule

/** 配置 ng-zorro-antd 国际化 **/
  providers   : [ { provide: NZ_I18N, useValue: zh_CN } ]

等等添加和依赖;
ng add ng-zorro-antd 和 手动添加使用npm install ng-zorro-antd --save,再手电动添加依赖是同样的效果!!!!!

此时重启项目,那么在app.component.html中,antd是已经生效的!=>不重启,antd没有生效的。

icon的使用:需要加上下面的配置,要不然icon不让用,报错;重新编译,icon是ok的了。

[@ant-design/icons-angular]: the icon step-backward-o does not exist or is not registered.
// angular.json:
"assets": [
              "src/favicon.ico",
              "src/assets",
              {
                "glob": "**/*",
                "input": "./node_modules/@ant-design/icons-angular/src/inline-svg/",
                "output": "/assets/"
              }
            ],
  • antd中组件的国际化问题:

初始项目的时候,给了默认的语言:app.module.ts:

/** 配置 angular i18n **/
import { registerLocaleData } from '@angular/common';
import zh from '@angular/common/locales/zh';

registerLocaleData(zh);

// @NgModule中:
  providers: [{ provide: NZ_I18N, useValue: zh_CN  }],

切换语言的时候:
app.component.html:

import {en_US, NzI18nService, zh_CN} from 'ng-zorro-antd';

constructor(private nzI18nService: NzI18nService) {
}
// 执行函数:当英文的时候切换为中文,其他情况下切换为英文!切换的时候,全局的组件都会生效的!!!!(所有使用antd组件的语言问题)
 switchLanguage() {
    if (this.nzI18nService.getLocale().locale == 'en') {
      this.nzI18nService.setLocale(zh_CN);
    } else {
      this.nzI18nService.setLocale(en_US);
    }
}
// en_US的时候,返回en;zh_CN的时候,返回zh-cn;
  • 页面中自定义字段的国际化问题:

参考:https://www.jianshu.com/p/7d1da3098625
https://blog.csdn.net/biangbiang_/article/details/80405667
https://blog.csdn.net/qq_36822018/article/details/81504473
如下:

//利用npm来安装ngx-translate依赖
npm install @ngx-translate/core --save
npm install @ngx-translate/http-loader --save

appModule中增加:

export function createTranslateLoader(http: HttpClient) {
  return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}

// import:
TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: createTranslateLoader,
        deps: [HttpClient]
      }
    })

在使用翻译的组件中:

constructor(private nzI18nService: NzI18nService,
              private router: Router,
              private translate: TranslateService) {
    this.translate.use('en');
  }

html中:
<span>{{ 'welcome '| translate}}</span>

注:welcome后面有空格,那么翻译的时候,直接是welcome,而不是取对应的语言值!!!!!!!!!

此时:只在appModule中加了TranslateModule,其他的模块中没有TranslateModule这个模块,使用的时候,会报错!translate找不到!所以各个模块要用翻译的话,需要单独依赖一下!跟antd一样的!

上面每个模块中都加上面的同样的内容比较麻烦,所以我们提出来放在一个模块中:
transitionModule:

export function createTranslateLoader(http: HttpClient) {
  return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}

@NgModule({
  declarations: [],
  imports: [
    CommonModule,
    // TranslateModule,
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: createTranslateLoader,
        deps: [HttpClient]
      }
    }),

  ],
  exports: [TranslateModule],   // 这一行必须加上,要不然报错!!!!!
})
export class TranslationModule {
  constructor(private translateService: TranslateService) {
    // --- set i18n begin ---
    // 添加语言支持
    this.translateService.addLangs(['zh', 'en']);
    // 设置默认语言,一般无法匹配的时候使用
    this.translateService.setDefaultLang('zh');
    const browserLang = this.translateService.getBrowserLang();
    console.log('浏览器的默认语言:', browserLang);
    this.translateService.use(browserLang.match(/zh|en/) ? browserLang : 'zh');
  }
}

tab页面的title也需要国际化的,appComponent:

ngOnInit() {
    // 也可以将语言存在缓存中,供切换语言时,其他模块同时读取到语言的变化
    // sessionStorage.setItem("language",'en');
    console.log(this.translateService.get('welcome'));
    this.translateService.get('title').subscribe((res) => {
      console.log(res);
      document.title = res;
    });


  }

刷新的时候,title怎么展示?

// 订阅语言切换事件  =>切换语言后,title也动态的改变
this.translateService.onLangChange.subscribe(res => {
  // 语言
  console.log('语言变化执行了', res);
  // this.translateService.use('en');
  if (res.lang == 'en') {
    document.title = 'cloud';
  } else if (res.lang == 'zh') {
    document.title = '云';
  } else {
    document.title = '云111';
  }

});

antd默认组件的语言:
appModule中注册语言是哪种 ?
各种语言字段对照antd的语言表,eg:中文:zh_CN;英文:en_US
修改默认语言:

app.module中:
// providers: [{ provide: NZ_I18N, useValue: en_US }],
providers: [{ provide: NZ_I18N, useValue: zh_CN }],

入场动画问题:
HTML:
找一个加载动画效果,id为:preloader,放在index.html中;
参考:https://www.cnblogs.com/lhb25/p/loading-spinners-animated-with-css3.html

增加service.ts文件:

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

@Injectable()
export class PreloaderService {
  private _selector = 'preloader';
  private _element: HTMLElement;

  constructor() {
    this._element = document.getElementById(this._selector);
  }

  show() {
    this._element.style['display'] = 'block';
  }

  hide() {
    this._element.style['display'] = 'none';
  }
}

在appModule中依赖这个service,
然后在appComponent中:

constructor(private nzI18nService: NzI18nService,
              public translateService: TranslateService,
              private preLoader: PreloaderService) {
  }
  ngAfterViewInit() {
    this.preLoader.hide();
  }

生成模块和组件:
默认都是从app开始,所以不用加app,直接就是app下的什么文件下,eg:我们是app/pages,直接从pages开头!!!

pages模块和组件:

ng g m pages --routing
ng g c pages --view-encapsulation None   // 样式怎么样选择都可以,可以不加后面的参数

登录模块和组件

ng g m pages/auth --routing
ng g c pages/auth --view-encapsulation None
ng g c pages/auth/components/login --view-encapsulation None

设备模块:

ng g m --routing pages/device-mgmt -d  // 模块
ng g c pages/device-mgmt --view-encapsulation None -d // 模块的主组件
ng g c pages/device-mgmt/components/device-list  // 模块的子组件


模块不会自动加载在模块中,所以在app.module中依赖pages.module

app.routing:

const routes: Routes = [
  {path: '', redirectTo: 'pages', pathMatch: 'full'},
  {path: '**', redirectTo: 'pages'}
];

pages.routing:

const routes: Routes = [
  {path: '', redirectTo: 'pages', pathMatch: 'full'},
  {
    path: 'pages',
    component: PagesComponent,
    children: [
      {path: '', redirectTo: 'device-mgmt', pathMatch: 'full'},
      {path: 'device-mgmt', loadChildren: './device-mgmt/device-mgmt.module#DeviceMgmtModule'},
    ]
  }
];

device-mgmt.module:

const routes: Routes = [
  {path: '', redirectTo: 'device-list', pathMatch: 'full'},
  {path: 'device-list', component: DeviceListComponent},
  {path: 'over-view', component: OverViewComponent},
];

报错:
找不到具体原因:

ERROR in Could not resolve module app/pages/auth/auth.module relative to app\pages\pages.module.ts

之前路由地址是:

{path: 'gyauth', loadChildren: 'app/pages/auth/auth.module#AuthModule'},

这么写不行,报上面的错误!!!修改为:

{path: 'gyauth', loadChildren: './auth/auth.module#AuthModule'},

路由跳转失败?为什么啊??没找到原因的!!!!!
原因:

检查下appModule中:pagesModule需要在appRouting上面,这样路由才可以生效!!!!(顺序的问题)

使用ngModel指令的时候,需要有FormsModule模块才可以,要不然报错:

core.js:12501 ERROR Error: Uncaught (in promise): Error: Template parse errors:
Can't bind to 'ngModel' since it isn't a known property of 'nz-date-picker'.

使用命令生成模块的时候:

ng g m translation  // 相当于  ng g m translation --flat false  即:
$ ng g m translation --flat false
CREATE src/app/translation/translation.module.ts (195 bytes)
// 会带有文件夹的!
// 没有文件夹,只有transtion这个ts文件
$ ng g m translation --flat true
CREATE src/app/translation.module.ts (195 bytes)

安装bootstrap 和normalize

npm install bootstrap --save
npm install --save normalize.css

styles.scss中:

@import "../node_modules/normalize.css/normalize.css";
@import "../node_modules/bootstrap/scss/bootstrap.scss";

app下新建:
theme>saas>_layout.scss,内容为:

body{
  min-width: 1200px;
}

theme>theme.scss,内容为:

@import "saas/layout";

在angular.json中引入:

 "styles": [
              "./node_modules/ng-zorro-antd/ng-zorro-antd.min.css",
              "src/app/theme/theme.scss",
              "src/styles.scss"
            ],

login页面:
header,content,footer:使用flex布局;
div里图片水平垂直居中:使用flex布局。(注意 justify-content: center;
align-items: center;在哪用的!!!!)
登录的form表单使用antd组件

滚动条的样式:

/*滚动条的样式*/
/*滚动条的w和h*/
::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}
/*滚动条的颜色*/
::-webkit-scrollbar-thumb {
  background: #8265d9;
  cursor: pointer;
}
/*滚动条的背景颜色*/
::-webkit-scrollbar-track {
  background: rgba(0,0,0,0.1);
}

登录加密:使用3des加密

npm install crypto-js --save

参考我的3des加密文章!

需要调用接口了,此时用了base-service,但是依赖appCommon,appCommon又依赖sessionStorage和base64的文件!
appModule中丢掉了:HttpModule;
service文件中有一个:import {Location} from ‘@angular/common’;,不知道干嘛用的,要写上,要不然报错!

调用接口的时候,404,因为还没代理呢!!!
新增proxy.conf.json文件:

// 其中三个auth是微服务名称,需要修改
{
    "/auth": {
        "target": "http://xxxxx.xxxxx.com",
        "secure": false,
        "changeOrigin": true,
        "pathRewrite": {
            "^/auth": "/auth"
        }
    }
}

package.json中,修改start的参数,走代理文件!

"scripts": {
    "ng": "ng",
    "start": "ng serve  --proxy-config proxy.conf.json --port 4200 --disable-host-check true",
	// .....
  },

ng build打包的时候,默认文件夹的目录结构是跟低版本ng不一样的,查看angular.json中:"outputPath": "dist/cloud",
之前都是直接在 dist下面,没有文件夹名称了,so修改outputPath的 值为:"dist"
重新build的时候报错:

ENOTEMPTY: directory not empty, rmdir 'C:\Users\xxxxx\Desktop\cloud\dist'

按理说需要:"rimraf": "rimraf", "rimraf": "2.6.1",,但是重新ng build后就没事了,没添加这个包!
npm scripts 使用指南
http://www.ruanyifeng.com/blog/2016/10/npm_scripts.html

登录的时候chrome警告,信息如下:

This page includes a password or credit card input in a non-secure context. A warning has been added to the URL bar. For more information, see https://goo.gl/zmWq3m.

参考:https://segmentfault.com/q/1010000008779480
没找到解决办法,不知道怎么回事!

commonApp模块:

ng g m --routing pages/basic-frwk -d  // 模块
ng g c pages/basic-frwk --view-encapsulation None -d // 模块的主组件
ng g c pages/basic-frwk/components/dashboard --view-encapsulation None -d  // 模块的子组件


pages里面写页面的 布局:使用antd的布局里面-自定义触发器的页面布局!
去掉encapsulate这个属性,然后样式生效!
==>并不太好使,因为头部没有固定,且内容较多时,滚动条也有问题!!

写好页面布局,需要些组件了,eg:ba-menu组件:

ng g m theme/nga --flat -d   // 共用组件的模块
ng g c theme/components/ba-menu --spec false   // 菜单组件

ngaModule:

@NgModule({
  declarations: [
    BaMenuComponent
  ],
  imports: [
    CommonModule,
    NgZorroAntdModule
  ],
  exports: [
    BaMenuComponent // 这个exports一定要导出一下,要不然找不到组件的!!!!!(组件名称是app-ba-menu,而不是ba-menu!!!)
  ]
})
export class NgaModule {
}

ba-menu组件:
ngFor和ngIf在同一个标签上是有问题的,所以用了ng-container标签,参考:
https://blog.csdn.net/wuyuxing24/article/details/82825608

menu组件完了以后,需要加icon了,引入iconfont,然后就是ba-page-top组件!

 类似资料: