<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>

                為了盡早的查看在真實后臺配合下的效果,我們在此進行集成測試。 ## 設置路由 在整個項目中集成某個組件的方法是為該方法定制一個對應的路由。這樣一來Angular便可以根據瀏覽器URI地址來找到對應的組件。 在上個章節中,我們使用了惰性加載的方式加了班級模塊,這在生產項目中是非常有必要的。惰性加載避免了用戶啟動時過多的加載項目文件,增加了整個應用的啟動速度。在網絡不理想的情況下將大幅提升用戶的使用感受。 為此我們仍然使用惰性加載的方式來加載學生模塊的各個組件。 ```typescript +++ b/first-app/src/app/app-routing.module.ts @@ -18,6 +18,10 @@ const routes: Routes = [ return m.ClazzModule; }) }, + { + path: 'student', + loadChildren: () => import('./student/student.module').then(m => m.StudentModule) + }, { ``` 然后在`StudentModule`中進行相應的路由設置。 ### 路由模塊 觀察App模塊與Clazz模塊的路由設置不難得出:App模塊使用了單獨的路由模塊`AppRoutingModule`,Clazz模塊直接將路由信息設置到了`ClazzModule`中。其實這兩種方式都是可以的,在實際的使用過程中,習慣于用哪種方式都可以,只需要保持整個項目的風格統一即可。 在此,我們展示如果手動在學生模塊中建立路由模塊,并將其應用到學生模塊中。 使用`shell`來到學生模塊所在文件夾,并執行如下命令: ```bash panjie@panjies-iMac student % ng g m studentRouting --flat Your global Angular CLI version (11.2.13) is greater than your local version (11.0.7). The local Angular CLI version is used. To disable this warning use "ng config -g cli.warnings.versionMismatch false". CREATE src/app/student/student-routing.module.ts (200 bytes) ``` 該命令將為我們當前文件夾下創建一個`student-routing.module.ts`文件: ```bash panjie@panjies-iMac student % tree -L 1 . ├── add ├── student-routing.module.ts ?? ├── student.component.css ├── student.component.html ├── student.component.spec.ts ├── student.component.ts └── student.module.ts ``` 文件內容如下: ```typescript import {NgModule} from '@angular/core'; import {CommonModule} from '@angular/common'; @NgModule({ declarations: [], imports: [ CommonModule ] }) export class StudentRoutingModule { } ``` 接著將該文件內容修改為: ```typescript import {NgModule} from '@angular/core'; import {Route, RouterModule} from '@angular/router'; import {StudentComponent} from './student.component'; import {AddComponent} from './add/add.component'; const routes = [ { path: '', component: StudentComponent }, { path: 'add', component: AddComponent } ] as Route[]; @NgModule({ imports: [ RouterModule.forChild(routes) ], exports: [RouterModule] }) export class StudentRoutingModule { } ``` 該模塊中的`imports`中引入了`RouterModule.forChild(routes)`,只所以能這樣使用是由于`forChild()`方法的返回值類型也相當于`RouterModule` 。如果直接`RouterModule`,則會得到一個空路由配置;但`forChild()`方法可以接收一個路由數組,該方法將返回一個具有路由配置的`RouterModule`。 該模塊接著在`exports`中聲明了`RouterModule`,其作用是將配置了路由的`RouterModule`拋出去(聲明為公有),這樣以來當其它模塊引入本模塊時,則相當于一并引入了配置了路由的`RouterModule`。 ### `?`與`!` 現在執行`ng s`,將得到如下錯誤警告(針對增加學生組件): ```bash Error: add/add.component.html:6:63 - error TS2531: Object is possibly 'null'. 6 <small class="text-danger" *ngIf="formGroup.get('name').invalid"> ~~~~~~~ ``` 稍微翻譯一下得知它在告訴我們說:在執行`formGroup.get('name').invalid`由于`formGroup.get('name')`的值可以是`null`,所以有可能發生`在null上調用invalid屬性`的異常。 上述信息是Angular根據類型檢查為我們提示的錯誤,追其原由是由于我們在C層定義`formGroup`的類型是`FormGroup`,而`FormGroup`中的`get()`方法的返回值聲明如下(了解即可): ```typescript /** * Retrieves a child control given the control's name or path. * * @param path A dot-delimited string or array of string/number values that define the path to the * control. * * @usageNotes * ### Retrieve a nested control * * For example, to get a `name` control nested within a `person` sub-group: * * * `this.form.get('person.name');` * * -OR- * * * `this.form.get(['person', 'name']);` */ get(path: Array<string | number> | string): AbstractControl | null; ?? ``` 該方法聲明其返回值可能為`null`,這也是為什么Angular會出現上述提示的原因:既然`get()`的返回值可能為`null`,那么一旦其值為`null`則必然會發生在`null`上讀取`xxx`屬性的異常。雖然對當前學生新增組件而言,我們在C層的構造函數中對`formGroup`的各項進行了初始化從而避免執行`get()`方法時返回`null`,但這個邏輯對于Angular的語法檢查器而言太難了。Angular的語法檢查僅能夠做到根據返回值的類型進行推導(這已經很偉大了)。 此時我們有兩種方案來解決當前警告,第一種是使用`?`標識符,它表示:如果當前值是一個對象,則繼續執行;否則中斷執行: ```html +++ b/first-app/src/app/student/add/add.component.html @@ -3,7 +3,7 @@ <label class="col-sm-2 col-form-label">名稱</label> <div class="col-sm-10"> <input type="text" class="form-control" formControlName="name"> - <small class="text-danger" *ngIf="formGroup.get('name').invalid"> + <small class="text-danger" *ngIf="formGroup.get('name')?.invalid"> 名稱不能為空 </small> </div> @@ -11,11 +11,11 @@ <div class="mb-3 row"> <label class="col-sm-2 col-form-label">學號</label> <div class="col-sm-10"> - {{formGroup.get('number').errors | json}} + {{formGroup.get('number')?.errors | json}} <input type="text" class="form-control" formControlName="number"> - <small class="text-danger" *ngIf="formGroup.get('number').invalid"> - <span *ngIf="formGroup.get('number').errors.required">學號不能為空</span> - <span *ngIf="formGroup.get('number').errors.numberExist">該學號已存在</span> + <small class="text-danger" *ngIf="formGroup.get('number')?.invalid"> + <span *ngIf="formGroup.get('number')?.errors?.required">學號不能為空</span> + <span *ngIf="formGroup.get('number')?.errors?.numberExist">該學號已存在</span> </small> </div> </div> @@ -23,9 +23,9 @@ <label class="col-sm-2 col-form-label">手機號</label> <div class="col-sm-10"> <input type="text" class="form-control" formControlName="phone"> - {{formGroup.get('phone').invalid}} - {{formGroup.get('phone').errors | json}} - <small class="text-danger" *ngIf="formGroup.get('phone').invalid"> + {{formGroup.get('phone')?.invalid}} + {{formGroup.get('phone')?.errors | json}} + <small class="text-danger" *ngIf="formGroup.get('phone')?.invalid"> 手機號格式不正確 </small> </div> ``` 第二種方式是使用`!`標識符,表示:我確認當前值必然是一個對象,請忽略掉對非object的判斷: ```typescript +++ b/first-app/src/app/student/add/add.component.html @@ -40,7 +40,7 @@ <label class="col-sm-2 col-form-label">班級</label> <div class="col-sm-10"> <app-clazz-select formControlName="clazzId"></app-clazz-select> - <small class="text-danger" *ngIf="formGroup.get('clazzId').invalid"> + <small class="text-danger" *ngIf="formGroup.get('clazzId')!.invalid"> 必須選擇班級 </small> </div> ``` 在生產項目中,應該根據實際情況來決定是使用`?`還是`!`。以當前學生新增組件為例,在執行`formGroup.get('xxx')`應該返回一個對象,如果沒有對象返回的話就說明我們的C層代碼邏輯錯了(比如漏寫了),則此時應該使用`!`;而代碼`formGroup.get('number').errors.numberExist`中的`errors`則會在發生錯誤時才會有值,未發生錯誤的話其值則是`null`,此時則應該使用`?`標識符。 所以`formGroup.get('number').errors.numberExist`的正確寫法應當是`formGroup.get('number')!.errors?.numberExist`。 請按上述規范修正學生新增組件中的V層代碼。 ### 引入路由 有了單獨的路由模塊后,便可以將其引入到學生模塊中了: ```typescript +++ b/first-app/src/app/student/student.module.ts @@ -5,6 +5,7 @@ import {ReactiveFormsModule} from '@angular/forms'; import { StudentComponent } from './student.component'; import {PageModule} from '../clazz/page/page.module'; import {RouterModule} from '@angular/router'; +import {StudentRoutingModule} from './student-routing.module'; @NgModule({ @@ -13,7 +14,8 @@ import {RouterModule} from '@angular/router'; CommonModule, ReactiveFormsModule, PageModule, - RouterModule + RouterModule, + StudentRoutingModule ] }) export class StudentModule { ``` 路由引入完成后,打開瀏覽器并訪問[http://localhost:4200/student](http://localhost:4200/student)來檢驗下自己的成果吧。 ![image-20210609101123561](6.assets/image-20210609101123561.png) ### 設置菜單 最后我們完善下菜單,使得點擊“學生管理”時跳轉http://localhost:4200/student: ```html +++ b/first-app/src/app/nav/nav.component.html @@ -18,7 +18,7 @@ <a class="nav-link" routerLink="clazz">班級管理</a> </li> <li class="nav-item"> - <a class="nav-link" href="#">學生管理</a> + <a class="nav-link" routerLink="student">學生管理</a> </li> <li class="nav-item" routerLinkActive="active"> <a class="nav-link" routerLink="personal-center">個人中心</a> ``` ## 測試 點擊新增按鈕后,將在控制臺得到以下信息: ![image-20210609103921300](6.assets/image-20210609103921300.png) 其實該錯誤信息我們的IDE早早的就在提示我們: ![image-20210609103951209](6.assets/image-20210609103951209.png) 產生該錯語的原因是由于當前模塊并不認識`app-clazz-select`選擇器。而產生該錯誤的原因是由于當前模塊并沒有引入`app-clazz-select`選擇器所在的模塊: ```typescript +++ b/first-app/src/app/student/student.module.ts @@ -6,6 +6,7 @@ import { StudentComponent } from './student.component'; import {PageModule} from '../clazz/page/page.module'; import {RouterModule} from '@angular/router'; import {StudentRoutingModule} from './student-routing.module'; +import {ClazzSelectModule} from '../clazz/clazz-select/clazz-select.module'; @NgModule({ @@ -15,7 +16,8 @@ import {StudentRoutingModule} from './student-routing.module'; ReactiveFormsModule, PageModule, RouterModule, - StudentRoutingModule + StudentRoutingModule, + ClazzSelectModule ] }) export class StudentModule { ``` 引入模塊后錯誤消失(可能需要重啟`ng s`)。 接著進行新增功能的測試,發現點擊保存按鈕后控制臺雖然打印成功,但卻未進行跳轉,修正如下: ```typescript +++ b/first-app/src/app/student/add/add.component.ts @@ -3,6 +3,7 @@ import {FormControl, FormGroup, Validators} from '@angular/forms'; import {YzValidators} from '../../yz-validators'; import {YzAsyncValidators} from '../../yz-async-validators'; import {StudentService} from '../../service/student.service'; +import {ActivatedRoute, Router} from '@angular/router'; @Component({ selector: 'app-add', @@ -12,7 +13,8 @@ import {StudentService} from '../../service/student.service'; export class AddComponent implements OnInit { formGroup: FormGroup; - constructor(private studentService: StudentService, private yzAsyncValidators: YzAsyncValidators) { + constructor(private studentService: StudentService, private yzAsyncValidators: YzAsyncValidators, + private router: Router, private route: ActivatedRoute) { this.formGroup = new FormGroup({ name: new FormControl('', Validators.required), number: new FormControl('', Validators.required, yzAsyncValidators.numberNotExist()), @@ -34,7 +36,7 @@ export class AddComponent implements OnInit { clazzId: number }; this.studentService.add(student) - .subscribe(success => console.log('保存成功', success), + .subscribe(success => this.router.navigate(['../'], {relativeTo: this.route}), error => console.log('保存失敗', error)); } ``` 跳轉修正后保存完學生后正常回跳到了學生列表界面。 隨后測試刪除、批量刪除、分頁功能等功能。 ![image-20210609155050370](https://img.kancloud.cn/18/39/1839701ccab5c120e0385ccf9c3e4847_2394x1006.png) 測試結果功能正常,集成測試結束。 ## 本節資源 | 鏈接 | 名稱 | | ------------------------------------------------------------ | -------- | | [https://github.com/mengyunzhi/angular11-guild/archive/step7.6.zip](https://github.com/mengyunzhi/angular11-guild/archive/step7.6.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>

                              哎呀哎呀视频在线观看