angular pitfalls

1 The new version of the route guard uses a function function because canActivate has been abandoned. However, the route object cannot be injected into its parameters like a class. How to realize the page jump in the first place of the route?


import { CanActivateFn, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { inject } from "@angular/core"

export const authguardGuard: CanActivateFn = (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => {
  console.log("route", route)
  console.log("state", state)
  const router: Router = inject(Router)
  if (localStorage.getItem("token")) {
    if (state.url == '/login') {
      router.navigate(['/home'])
      return true
    } else {
      return true
    }
  } else {
    console.log("1")

    if (state.url !== "/login") {
      router.navigate(['/login'])
    }
    return true
  }
};

Here, inject is used to force injection to obtain the router object. In this way, routing jumps can be achieved

2 For lazy loading of routes, relevant modules need to be introduced in app.module.ts and the current module.ts at the same time. Otherwise, an error will be reported. for example

'nz-form-control' is not a known element:

The reason is that NzFormModule is only introduced in app.moudule.tsz, but it is not introduced in the module of the component of the current page, resulting in an error being reported all the time.

3 For the nz-space component in nozzor-antd to take effect, *nzSpaceItem must be added

4. How to obtain the attribute value of the current object through the traversed data in the template, as follows:

constructor(private fb:FormBuilder){
    this.validateForm=this.fb.group({
      storename:[''],
      tableSize:this.fb.group({
          toggle:['true'],
          groupSize:this.fb.array([
            this.fb.group({
              cate:['indoor'],
              title_en:[''],
              title_zh:[''],
              
            }),
            this.fb.group({
              cate:['outdoor'],
              title_en:[''],
              title_zh:[''],
              
            }),
          ]),
      }),
      

    })
  }


 <form  class="store_generate_form" nz-form [formGroup]="validateForm" (ngSubmit)="submitForm()">
            <nz-form-item>
                <nz-form-label [nzSpan]="8" nzFor="storename">店铺名称</nz-form-label>
                <nz-form-control [nzSpan]="16">
                <input nz-input name="storename" type="storename" formControlName="storename">
                </nz-form-control>
            </nz-form-item >
             <div>
                <nz-form-item>
                     <nz-tab [nzTitle]="group.value.cate" *ngFor="let group of groupSize.controls; let i = index" [formGroupName]="i">
                 </nz-form-item>   
            </div>    

The name of the tab in the tab page here should be read based on the cate field. The method here is to obtain it through [nzTitle]="group.value.cate". For each control, there is a value attribute underneath it, through which the original json data object can be obtained.

6 How to add extra content to tabs in zorro?

  <nz-tabset   nzType="card" formArrayName="groupSize" 
               [nzTabBarExtraContent]="extraContent" (nzAdd)="addTab()"
  >

                <ng-template #extraContent>
                                <button nz-button nzType="dashed">Add</button>
                </ng-template>
                <nz-tab nzIcon="book" >
                         <ng-template nz-tab>
                                tab中的内容xxxx
                        </ng-template>


                </nz-tab>

                <ng-container *ngTemplateOutlet="extraContent"></ng-container>
  </nz-tabset>

By defining tabExtraContenta template reference that contains custom text content. Then, nz-tabsetuse <ng-container>the element internally and use *ngTemplateOutletdirectives to tabExtraContentrender the referenced content at the specified location on the page.

This way you can replace the default "+" style with custom text ("Add" button) and have it render correctly in the page.

7. When adding group data to the formArray object, remember that the field names of each item must correspond, otherwise an error will be reported.

RROR Error: Cannot find control with path: 'tableSize -> groupSize -> 0 -> tableSize -> 2 -> minPerson'

For example:

<nz-tab nzIcon="book" [nzTitle]="group.value.cate" *ngFor="let group of groupSize.controls; let i = index" [formGroupName]="i">
                                    <div formArrayName="tableSize">  
                                            <ng-template nz-tab>
                                                <nz-form-item *ngFor="let table of tableSizeControls(i)?.['controls']; let j = index" [formGroupName]="j">
                                                    <nz-form-control>
                                                        <div class="danamic_group"> 
                                                            <div class="danamic_group_item">
                                                                <nz-input-group nzAddOnBefore="Key" >
                                                                    <input nz-input type="text" nz-input  formControlName="size"/>
                                                            </nz-input-group>
                                                            </div>
                                                            <div class="danamic_group_item" >
                                                                <nz-input-group nzAddOnBefore="EN" >
                                                                    <input nz-input type="text" nz-input  formControlName="desc_en"/>
                                                            </nz-input-group>
                                                            </div>
                                                            <div class="danamic_group_item" >
                                                                <nz-input-group nzAddOnBefore="CH">
                                                                    <input nz-input  type="text" nz-input  formControlName="desc_zh"/>
                                                            </nz-input-group>
                                                            </div>
                                                            <div class="danamic_group_item" >
                                                                <nz-input-group nzAddOnBefore="number">
                                                                    <input nz-input type="text" nz-input  formControlName="number"/>
                                                            </nz-input-group>
                                                            </div>
                                                            <div class="danamic_group_item" >
                                                                <nz-input-group >
                                                                    <nz-input-number [nzMin]="1" type="text" nz-input  formControlName="minPerson"/>
                                                            </nz-input-group>
                                                            </div>
                                                            <div class="danamic_group_item">
                                                                <nz-input-group >
                                                                    <nz-input-number [nzMin]="1" type="text" nz-input  formControlName="maxPerson"/>
                                                            </nz-input-group>
                                                            </div>
                                                        </div>
                                                    </nz-form-control>
                                                </nz-form-item>  
                                            </ng-template>                  
                                    </div>
                            </nz-tab>

Note that the last two formControlNames in ngfor are minPerson and maxPerson. Next, add a new data to the formArray in the js file.


  get groupSize(): FormArray {  
    return this.validateForm.get('tableSize.groupSize') as FormArray;
  }

  tableSizeControls(index:number): FormArray {
    let list=this.validateForm.get('tableSize.groupSize') as FormArray;
    let lastlist=list.controls[index].get('tableSize') as FormArray ||[]
    return lastlist
  }
    add(){
    //先找到是indoor还是outdoor的tablsesize
    console.log("this.activeTab",this.actvieTabIndex)
    let newdata=this.fb.group({
          size: [""],
          desc_en:[""],
          desc_zh: [""],
          number:[''],
          preTitle: [""],
          maxPerson: [],
    })

    let curTableSizeArr=this.tableSizeControls(this.actvieTabIndex) as FormArray
    console.log("curTableSizeArr",curTableSizeArr)
    curTableSizeArr.push(newdata)
    console.log("curTableSizeArr",curTableSizeArr)
  }
  remove(){   
      let curTableSizeArr=this.tableSizeControls(this.actvieTabIndex) as FormArray
      curTableSizeArr.removeAt(curTableSizeArr.length-1)
 
  }

Note that the field in the data newdata we defined in the add function does not have minPerson, and an error will be reported at this time. At this point we need to verify the fields. We change perTtile to minPerson later. The error disappears

8 How does the interceptor in Angular simplify the data returned by the backend?

If the data level returned by the backend is too deep, how to simplify the level and get the simplified data in a specific request?

@Injectable()
export class AuthInterceptorInterceptor implements HttpInterceptor {

  constructor() {}

  intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    let reqClone=request.clone({
      setHeaders:{token:localStorage.getItem("token")||""}
    })
    return next.handle(reqClone).pipe(
      
       map((event:any)=>{
         if(event instanceof HttpResponse){
           event=event.clone({body:event.body.data.data.data})
         }
         return event
      }),
      catchError((err:HttpErrorResponse)=>{
        console.log("err",err);
        throw err
      })
    )
  }
}

The core lies in the map function. At the same time, it should be noted that if we want to change the return value, we must use the clone method. Directly changing the event is invalid.

9: app.module.ts introduced ReactiveFormsModule and FormsModule, but still reported an error: Can't bind to 'formGroup' since it isn't a known property of 'form'.

Reason: The page component is not declared in app.module.ts

@NgModule({
  declarations: [
    AppComponent,
    LayoutComponent,
    HomeComponent,
    NewsComponent,
    NotfoundComponent,
    StoreformComponent,
    AboutComponent,
    LoginComponent,
    FormpageComponent   //注意这里
    // AdminComponent
  ],

10:ERROR NullInjectorError: R3InjectorError(StoreEditModule)[NzMessageService -> NzMessageService -> NzMessageService -> NzMessageService]: 
  NullInjectorError: No provider for NzMessageService!

When introducing NzMessageService. Report an error. The reason for this is that there is no setting in the private option of the current module:

 constructor(private fb:FormBuilder,private message:NzMessageService){
    this.validateForm=this.fb.group({
      storename:[''],
      
    })
  }
    ngOnInit(){
      const id = this.message.loading('加载中..', { nzDuration: 0 }).messageId;
      setTimeout(() => {
        this.message.remove(id);

        //回显赋值
        //this.validateForm.patchValue(data)


      }, 3000);
  
    }
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { StoreEditRoutingModule } from './store-edit-routing.module';
import { StoreEditComponent } from './store-edit.component';

import { ReactiveFormsModule, FormsModule, FormGroup, FormBuilder, FormArray } from '@angular/forms';
import { NzFormModule} from 'ng-zorro-antd/form';

import { NzMessageService } from 'ng-zorro-antd/message';
@NgModule({
  declarations: [
    StoreEditComponent
  ],
  imports: [
    CommonModule,
    StoreEditRoutingModule,
    
    NzBreadCrumbModule,
  ],
  providers: [{provide: NzMessageService}], //这里是核心
})
export class StoreEditModule { }

Guess you like

Origin blog.csdn.net/baidu_41601048/article/details/131810677