<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                # 代碼重構 “如果尿布臭了,就換掉它。”-語出 Beck 奶奶,論撫養小孩的哲學。重構,絕對是軟件開發寫程序過程中最重要的事之一。沒有重構的項目隨著時間的推移必然會成為老太太的裹腳布 ---- 又臭又長。 下面,我們按以下幾步對當前項目進行重構,以使得整個項目看起來更易懂,修改其來更容易。 ## 建立實體類 建立實體類(接口)將后臺API交互過程中對返回的數據進行了規范。這種規范使得團隊成員再與后臺交互時完全的規避拼寫錯誤,即使錯了,整個項目對某個字段的修改也僅僅需要一次。 > 實體類:由于該類的作用是對應后臺返回的**實體entity**,所以我們把這種類稱為實體類。 本節在新建班級時,并沒有創建對應的班級實體類,實雖然并不影響當前功能實現,但明顯**班級實體**日后還需要在**班級列表**,**班級編輯**中被再次使用。我們來到src/app/entity文件夾,然后執行`ng g class Clazz`命令來生成一新類: ```bash panjie@panjies-Mac-Pro entity % ng g class clazz CREATE src/app/entity/clazz.spec.ts (150 bytes) CREATE src/app/entity/clazz.ts (23 bytes) ``` 然后在`clazz`實體類中增加`id`,`name`,`teacher`屬性: ```typescript import {Teacher} from './teacher'; export class Clazz { id: number; name: string; teacher: Teacher; } ``` 然后如下初始化構造函數: ```typescript constructor(data = {} ① as ② { id?③: number; name?③: string; teacher?③: Teacher; }) { this.id = data.id as number; ④ this.name = data.name as string; this.teacher = data.teacher as Teacher; } ``` - ① 使用`data = {}`來初始化一個帶有默認值的參數。 - ② 使用as來進行轉換,規定參數的類型 - ③ ? 號的作用是指該屬性可有可無。 - ④ 由于③的存在,`data.id`的值可能是`undefined`,這里使用`as number`防止報類型不匹配的錯誤。 哪此一來,我們便可以使用如下語句來實例化`Clazz`了: ```typescript +++ b/first-app/src/app/entity/clazz.spec.ts @@ -1,10 +1,12 @@ import {Clazz} from './clazz'; +import {Teacher} from './teacher'; describe('Clazz', () => { it('should create an instance', () => { expect(new Clazz()).toBeTruthy(); expect(new Clazz({id: 123})).toBeTruthy(); - expect(new Clazz()).toBeTruthy(); - expect(new Clazz()).toBeTruthy(); + expect(new Clazz({name: 'test'})).toBeTruthy(); + expect(new Clazz({teacher: {id: 1} as Teacher})).toBeTruthy(); + expect(new Clazz({id: 123, name: 'test', teacher: {id: 1} as Teacher})).toBeTruthy(); }); }); ``` 將`it`變更為`fit`,執行單元測試,通過: ![image-20210322143937732](https://img.kancloud.cn/b5/2d/b52d10f27c6a3b05328e16f526843bfc_684x138.png) 實體類有了,下一步我們將實體類應該到對應的組件中: ```typescript +++ b/first-app/src/app/clazz/add/add.component.ts +import {Clazz} from '../../entity/clazz'; onSubmit(): void { const newClazz = new Clazz({ name: this.clazz.name, teacher: { id: this.clazz.teacherId } as Teacher }); ``` 此時如果我們不小心把`name`拼寫為`naem`,則編輯器會實時地報告一個錯誤: ![image-20210322144256987](https://img.kancloud.cn/31/7a/317a8a145191578bb1cda0c512fec2be_2580x286.png) ### 重構/src/app/entity/teacher.ts 既然如上的構造函數這么優秀,我們打開`/src/app/entity/teacher.ts`,按上述方法重寫一便構造函數: ```typescript +++ b/first-app/src/app/entity/teacher.ts @@ -9,12 +9,13 @@ export class Teacher { sex: boolean; username: string; - constructor(id: number, email: string, name: string, password: string, sex: boolean, username: string) { - this.id = id; - this.email = email; - this.name = name; - this.password = password; - this.sex = sex; - this.username = username; + constructor(data = {} as { + id?: number, email?: string, name?: string, password?: string, sex?: boolean, username?: string}) { + this.id = data.id as number; + this.email = data.email as string; + this.name = data.name as string; + this.password = data.password as string; + this.sex = data.sex as boolean; + this.username = data.username as string; } } ``` typescript這個強類型的語言,能夠快速發現在重構過程中發生的問題。上述構造函數重構后,在啟用`ng t`的控制臺將得到如下錯誤提醒: ```bash Error: src/app/entity/teacher.spec.ts:5:27 - error TS2554: Expected 0-1 arguments, but got 6. 5 expect(new Teacher(1, 'email', 'name', 'password', true, 'username')).toBeTruthy(); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ``` 打開相應的錯誤文件,修正如下: ```typescript +++ b/first-app/src/app/entity/teacher.spec.ts @@ -1,7 +1,14 @@ -import { Teacher } from './teacher'; +import {Teacher} from './teacher'; describe('Teacher', () => { it('should create an instance', () => { - expect(new Teacher(1, 'email', 'name', 'password', true, 'username')).toBeTruthy(); + expect(new Teacher({ + id: 1, + email: 'email', + name: 'name', + password: 'password', + sex: true, + username: 'username' + })).toBeTruthy(); }); }); ``` 新的構造函數有了,歷史上一些不太好的寫法終于可心退出舞臺了: ```typescript +++ b/first-app/src/app/clazz/add/add.component.ts @@ -29,9 +29,7 @@ export class AddComponent implements OnInit { onSubmit(): void { const newClazz = new Clazz({ name: this.clazz.name, - teacher: { - id: this.clazz.teacherId - } as Teacher + teacher: new Teacher({id: this.clazz.teacherId}) }); this.httpClient.post(this.url, newClazz) .subscribe(clazz => console.log('保存成功', clazz), ``` ```typescript +++ b/first-app/src/app/login/login.component.ts @@ -8,7 +8,7 @@ import {Teacher} from '../entity/teacher'; styleUrls: ['./login.component.css'] }) export class LoginComponent implements OnInit { - teacher = {} as Teacher; + teacher = new Teacher(); @Output() beLogin = new EventEmitter<Teacher>(); ``` ## 剝離測試類 在進行MockApi的過程中,我們在`clazz/add/add.component.mock-api.spec.ts`建立了兩個模擬API用的內部類`ClazzMockApi`、 `TeacherMockApi`,其它成員不會關注到此內部類的存在,同時將模擬班級與模擬教師放在一起,也不利于管理。 為此,我們在src/app下新建mock-api文件夾,然后將兩個內部類移動過去: ```bash panjie@panjies-Mac-Pro app % pwd /Users/panjie/github/mengyunzhi/angular11-guild/first-app/src/app panjie@panjies-Mac-Pro app % tree mock-api mock-api ├── clazz.mock.api.ts └── teacher.mock.api.ts 0 directories, 2 files ``` clazz.mock.api.ts內容如下: ```typescript import {ApiInjector, MockApiInterface, randomNumber, RequestOptions} from '@yunzhi/ng-mock-api'; /** * 班級模擬API */ export ?? class ClazzMockApi implements MockApiInterface { getInjectors(): ApiInjector<any>[] { return [ { method: 'POST', url: 'clazz', result: (urlMatches: string[], options: RequestOptions) => { console.log('接收到了數據請求,請求主體的內容為:', options.body); const clazz = options.body; if (!clazz.name || clazz.name === '') { throw new Error('班級名稱未定義或為空'); } if (!clazz.teacher || !clazz.teacher.id) { throw new Error('班主任ID未定義'); } return { id: randomNumber(), name: '保存的班級名稱', createTime: new Date().getTime(), teacher: { id: clazz.teacher.id, name: '教師姓名' } }; } } ]; } } ``` 該類需要被本文件以外的文件`import`,所以必須使用`export`關鍵字 ?? 。 teacher.mock.api.ts內容如下: ```typescript import {ApiInjector, MockApiInterface, randomNumber} from '@yunzhi/ng-mock-api'; /** * 教師模擬API */ export ?? class TeacherMockApi implements MockApiInterface { getInjectors(): ApiInjector<any>[] { return [{ // 獲取所有教師 method: 'GET', url: 'teacher', result: [ { id: randomNumber(), name: '教師姓名1' }, { id: randomNumber(), name: '教師姓名2' } ] }]; } } ``` 最后對原`clazz/add/add.component.mock-api.spec.ts`重構: ```typescript +++ b/first-app/src/app/clazz/add/add.component.mock-api.spec.ts @@ -3,6 +3,8 @@ import {ComponentFixture, TestBed} from '@angular/core/testing'; import {HTTP_INTERCEPTORS, HttpClientModule} from '@angular/common/http'; import {ApiInjector, MockApiInterceptor, MockApiInterface, randomNumber, RequestOptions} from '@yunzhi/ng-mock-api'; import {FormsModule} from '@angular/forms'; +import {ClazzMockApi} from '../../mock-api/clazz.mock.api'; +import {TeacherMockApi} from '../../mock-api/teacher.mock.api'; describe('clazz add with mockapi', () => { let component: AddComponent; @@ -38,61 +40,3 @@ describe('clazz add with mockapi', () => { fixture.autoDetectChanges(); }); }); - -/** - * 班級模擬API - */ -class ClazzMockApi implements MockApiInterface { -請將本行及以下代碼全部刪除,限于篇幅,略過. ``` 好了,終于不那么過分的不合格了,就到這里。 ## 本節作業 項目中仍然存在待重構的`Teacher`,請嘗試找到它們并完成重構。 | 名稱 | 地址 | | ---------------- | ------------------------------------------------------------ | | TypeScript模塊 | [https://www.tslang.cn/docs/handbook/modules.html](https://www.tslang.cn/docs/handbook/modules.html) | | 本節源碼(含答案) | [https://github.com/mengyunzhi/angular11-guild/archive/step6.1.7.zip](https://github.com/mengyunzhi/angular11-guild/archive/step6.1.7.zip) |
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看