javascript - ng build --prod sırasında doğrulama yönergesindeki tüm parametreleri çözemiyor


Aşağıdaki soruları inceledim ancak herhangi bir çözüm bulamadım.

  • Angular 4 yönlendirici hatası: Yönlendirici için tüm parametreler çözümlenemiyor
  • Özel yönerge için tüm parametreler çözümlenemiyor

Benzersiz permalink'i doğrulamak için özel bir doğrulama yönergesi oluşturdum. Bu kod düzgün çalışıyor ama üretim için bir derleme yapmaya çalıştığımda bana şu hatayı veriyor:-

HATA : E:/Manish/Projects/ampleAdmin/src/app/shared/permalink-validation.directive.ts dosyasında UniquePermalinkValidatorDirective için tüm parametreler çözülemedi: ([object Object], ?).

permalink-doğrulama.directive.ts

import { Directive } from '@angular/core';
import { AsyncValidator, AbstractControl, ValidationErrors, NG_ASYNC_VALIDATORS, AsyncValidatorFn } from '@angular/forms';
import { Observable, of } from 'rxjs';
import { map } from 'rxjs/operators';
import * as qs from 'qs';
import { PageService } from '../services/page.service';
import { IPage } from '../client-schema';

export function UniquePermalinkValidator(pageService: PageService, page: IPage): AsyncValidatorFn {
  return (ctrl: AbstractControl): Promise<ValidationErrors | null> | Observable<ValidationErrors | null> => {
    if (!(ctrl && ctrl.value)) { return null; }

    const cond: any = {
      where: {
        permalink: ctrl.value
      }
    };

    if (page && page.id) {
      cond.where.id = { nin: [page.id]};
    }
    const query = qs.stringify(cond, { addQueryPrefix: true });

    return pageService.getPageCount(query).pipe(
      map(res => {
        return res && res.count ? { uniquePermalink: true } : null;
      })
    );
  };
}

@Directive({
  selector: '[appUniquePermalink]',
  providers: [{ provide: NG_ASYNC_VALIDATORS, useExisting: UniquePermalinkValidatorDirective, multi: true }]
})
export class UniquePermalinkValidatorDirective implements AsyncValidator {

  constructor(private pageService: PageService, private page: IPage) { }

  validate(ctrl: AbstractControl): Promise<ValidationErrors | null> | Observable<ValidationErrors | null> {
    return UniquePermalinkValidator(this.pageService, this.page)(ctrl);
  }
}

sayfa.component.ts

import { Component, OnInit, TemplateRef } from '@angular/core';
import * as _ from 'lodash';
import { NotifierService } from 'angular-notifier';
import { BsModalService, BsModalRef } from 'ngx-bootstrap/modal';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { IPage } from 'src/app/client-schema';
import { Utils } from 'src/app/shared/utils';
import { PageService } from 'src/app/services/page.service';
import { UniquePermalinkValidator } from 'src/app/shared/permalink-validation.directive';

@Component({
  selector: 'app-page',
  templateUrl: './page.component.html',
  styleUrls: ['./page.component.css']
})
export class PageComponent implements OnInit {

  private notifier: NotifierService;

  pageForm: FormGroup;
  pageDetail: IPage;

  isAddFold = false;
  isEditFold = false;
  editFoldIndex = -1;

  constructor(
    private pageService: PageService,
    private notifierService: NotifierService,
    private modalService: BsModalService,
    private formBuilder: FormBuilder,
  ) {
    this.notifier = notifierService;
  }

  initPageForm() {
    this.pageForm = this.formBuilder.group({
      name: ['', [Validators.required, Validators.minLength(2), Validators.maxLength(250)]],
      permalink: ['', [Validators.required], UniquePermalinkValidator(this.pageService, this.pageDetail)],
      folds: [
        []
      ],
      data: null,
      status: true
    });
  }
}

Add/Edit sayfası için tek bir form kullanıyorum, bu yüzden bir sayfayı düzenlerken kalıcı bağlantıya izin vermek için kayıt detaylarını zorunlu kılmam gerekiyor.

Mevcut sayfa detaylarını direktife aktarmanın bir yolu var mı?

Cevap #1

Verilen

export function UniquePermalinkValidator(pageService: PageService, page: IPage): AsyncValidatorFn {
  // ...
}

Ve verildi

@Directive({
  selector: '[appUniquePermalink]',
  providers: [{ provide: NG_ASYNC_VALIDATORS, useExisting: UniquePermalinkValidatorDirective, multi: true }]
})
export class UniquePermalinkValidatorDirective implements AsyncValidator {    
  constructor(private pageService: PageService, private page: IPage) {}
  // ...
}

Ve IPage'in yalnızca şuna göre tanımlandığı göz önüne alındığında

export interface IPage {
  id: number;
  // ...
}

O zaman UniquePermalinkValidatorDirective tanım gereği çalışmayacak ve tarif edilen şekilde başarısız olacaktır.

interface, sadece tip alanında bir şey tanımlar, değer alanında değil ve bu nedenle herhangi bir çalışma zamanı varlığı yoktur. Bu, değer pozisyonunda kullanılamayacağı anlamına gelir.

Özünde, Angular'ın bağımlılık enjeksiyonu sistemi yapıcı parametrelerinin tipini okur ve değer alanında buna karşılık gelen bir isimli bildirim olduğunda, enjeksiyon belirteci olarak o isimle eşleşen değeri kullanır.

Örneğin, aşağıdaki

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

@Injectable() export class Service {
    constructor(http: Http) {}
}

aynı zamanda yazılabilir

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

export class Service {
    constructor(@Inject(Http) http: ThisTypeIsArbitraryWithRespectToInjection) {}
}

aynı anlama geliyor

Dikkat edin, Http bir argüman olarak Inject'e geçiliyor. Ancak Inject(IPage), burada IPage bir interface olduğunda, hatalıdır.

@Inject(ProviderToken) öğesinin temel amaçlarından biri, sizin durumunuzdaki gibi durumlarda, işaretlenmiş parametrenin türünden bağımsız olarak bir sağlayıcı enjekte etmeye izin vermektir.

Bu nedenle, buna benzer bir şeye ihtiyacınız var

constructor(@Inject(pageToken) page) {}

Bu, bir token tanımlamanız ve enjeksiyon yapılabilen bir sağlayıcıyı kaydetmek için kullanmanız gerektiği anlamına gelir.

Yine de yazabilir ve yazmalı.

constructor(@Inject(pageToken) page: IPage) {}

Parametreye bir tür vermek için, ancak bu tür parametre için verilen değerle ilgisizdir.

Örneğin

import {InjectionToken, NgModule} from '@angular/core';

export const pageToken = new InjectionToken<IPage>('Page');

@NgModule({
  providers: [
    {
      provide: pageToken,
      useFactory: functionReturningAPage
    }
  ]
 }) export class // ...