本周使用angular7所遇到的一些問題


前言

本周在使用angular7所遇到的一些問題,學習是不斷的循序漸進的過程,在本周完成對應的工作后,也要抽出一些時間用來學習,比較我們公司10點上班,我一般9點就會到,在這一個小時內看看博客,寫寫筆記,學習下angular7,antd框架的一些問題,

打包問題

angular.json

     "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist",   //去掉 dist/后面對應的東西

package.json
  "build": "ng build --prod --build--optimizer "    
              
index.html
     <base href="/">  //跟后台確定好服務器的地址並且填在這里

反向代理

在根目錄新建 proxy.config.json

{
  "/api": {
    "target": "http://a.itying.com",
    "secure": "false",
    "changeOrigin": true
  }
}

package.json

"start": "ng serve --proxy-config proxy.conf.json", 
    
//注意使用 npm run start 或者使用 yarn start  
//我犯了一個錯誤使用 ng serve  一直報錯總是不知道原因
//使用的時候
/api/productlist   //地址頭部為 /api就行啦

使用 ng-zorro-antd

首先說一下angular7對新手很不友好,建議學習的時候盡量按照vue的思路去想問題,然后再考慮angular7是怎么實現的,因為國內ng的資料實在太少

ng  add ng-zorro-antd
//建議使用less,我使用scss一直報錯,都懵逼的不知道原因
//如果使用scss用全局配置下node-sass的鏡像下載
修改默認使用yarn 下載
ng config -g cli.packageManager yarn
//如果讓yarn支持 node-sass
yarn config set sass-binary-site http://npm.taobao.org/mirrors/node-sass
第一個y 圖標
第二個n  選擇cn
不行的話就cnpm  install node-sass

或者直接使用
ng new static --style less
cd static
ng add ng-zorro-antd

angular-cli升級

# 卸載現有angular-cli
npm uninstall -g angular-cli
# 清空cache
npm cache clean -f
# 升級
npm install -g @angular/cli@latest
# 升級到固定版本號
npm install -g @angular/cli@版本號 

使用ng-zorro-antd的樣式

::ng-deep 改樣式

導入第三方庫

angular.json
styles中就是我們要引入的css
scripts中就是我們要引入的js
詳細配置文件解釋
https://www.jianshu.com/p/1c3d13af4f88

我是這樣使用的
yarn add axios -S

import * as axios from 'axios'
//暫時還沒發現報錯

//下面還有一個標准的例子
cnpm install qs -S
cnpm install @types/qs -S
在angular.json引入
 "scripts": [
              "./node_modules/qs/dist/qs.js"
            ],
在 tsconfig.app.json引入
"types": ["qs"]
所在的組件.ts
import * as qs from 'qs';   
 console.log(qs.stringify({name: 'age', age: 12}));

封裝http

把公共的部分放在服務里面

  get(api, params = {}) {
    return new Promise((resolve, reject) => {
      const getString: string = api + qs.stringify(params);
      this.http.get(getString).subscribe((response) => {
        resolve(response);
      }, (rej) => reject(rej));
    });
  }

  post(api, params = {}) {
    return new Promise((resolve, reject) => {
        const httpOptions = {
             headers: new HttpHeaders({ 'Content-Type': 'application/json;application/x-www-form-urlencodeed; charset=utf-8'})
        };
      const postString: string = api + qs.stringify(params);
      this.http.post(postString, httpOptions).subscribe(response => {
        resolve(response);
      }, rej => reject(rej));
    });
  }

ng-zorro 布局篇

    <div nz-row>
      <div nz-col nzSpan="12">col-12</div>
      <div nz-col nzSpan="12">col-12</div>
    </div>
父盒子帶有 nz-row 子盒子帶有nz-col,因為24柵格,nzSpan="6"

柵格常常需要間隔 nzGutter
父元素
<div nz-row nzGutter="16">  推薦 8n+8
 
左右偏移
子盒子   nzoffset="4"

ng-zorro Flex布局

父元素添加 nzType="flex"
水平方向  nzJustify=""  start,center,end,space-between,space-around
<div nz-row nzType="flex" nzJustify="start">
        <div nz-col nzSpan="4">col-4</div>
垂直方向 nzAlign=""  top  middle  bottom
 <div nz-row nzType="flex" nzJustify="space-around" nzAlign="middle">

在使用路由默認處於激活的狀態

<a routerLink="/a/b" routerLinkActive="active" [routerLinkActiveOptions]="{exact:
true}">B鏈接</a>

https://majing.io/posts/10000019031169

表單

說實話表單這塊內容有時候會讓你感覺到頭大

個人首先過一遍官網的表單,然后再來學antd的表單

(ngModelChange)="add()" 監控input的狀態
//提交
<form nz-form [formGroup]="validateForm"
      (ngSubmit)="submitForm($event, validateForm.value)">
 提交
   submitForm = ($event: any, value: any) => {
    $event.preventDefault();
    for (const key in this.validateForm.controls) {
      this.validateForm.controls[key].markAsDirty();
      this.validateForm.controls[key].updateValueAndValidity();
    }
    console.log(value);
  };
重置狀態

resetForm(e: MouseEvent): void {
    e.preventDefault();
    this.validateForm.reset();
    for (const key in this.validateForm.controls) {
      this.validateForm.controls[key].markAsPristine();
      this.validateForm.controls[key].updateValueAndValidity();
    }
  }

<input formControlName="password" //填寫雙向綁定的參數>

備注框
  <textarea formControlName="comment" nz-input rows="2" placeholder="write any thing">
最后的提交按鈕和重置按鈕
  <nz-form-item>
    <nz-form-control [nzOffset]="7" [nzSpan]="12">
      <button nz-button nzType="primary"
              [disabled]="!validateForm.valid">Submit
      </button>
      <button nz-button (click)="resetForm($event)">Reset</button>
    </nz-form-control>
  </nz-form-item>

學習的時候看的,不然太多了,你會不理解

<form nz-form  [formGroup]="validateForm" (ngSubmit)="submitForm()">
      <nz-form-item>
    	 <nz-form-label [nzSm]="8" nzRequired>密碼</nz-form-label>
		 <nz-form-control>//表單域
             <input nz-input formControlName="userName" placeholder="提示的信息" />
             <nz-form-explain *ngIf="validateForm.get('userName')?.dirty && 					validateForm.get('userName')?.errors" >我是錯誤的信息</nz-form-explain>
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
 validateForm: FormGroup;
  submitForm(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
  }
  constructor(private fb: FormBuilder) {}
  ngOnInit(): void {
    this.validateForm = this.fb.group({
      userName: [null, [Validators.required]],
      password: [null, [Validators.required]],
      remember: [true],
                email: [null, [Validators.required,Validators.pattern(/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/)]],
//正則驗證
                    函數判斷
      confirm: ['', [this.confirmValidator]],           
    });
  }
   confirmValidator = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return { required: true };
    } else if (control.value !== this.validateForm.controls.password.value) {
      return { confirm: true, error: true };
    }
    return {};
  };


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM