Наследование шаблонов компонентов Angular - PullRequest
0 голосов
/ 24 марта 2020

Я использую наследование компонентов для создания некоторых форм для разных компонентов. Как сейчас, формы для обоих компонентов абсолютно одинаковы, поэтому я ссылался непосредственно на родителя. html.

Хотя он работает нормально, я не смог бы расширить форму для дочернего компонента, если это необходимо, поэтому я попытался это сделать:

@Component({
selector: 'edit-supplier',
template: `<edit-company></edit-company>`,
//templateUrl: '../../models/components/edit-company/edit-company.component.html',
styleUrls: ['./edit-supplier.component.css']
})

Кажется, что родительский шаблон выглядит как Однако я хотел, чтобы внедрение зависимостей не работало.

export class EditSupplierComponent extends EditCompanyComponent {
constructor(supplierService: SuplierService,
        router: Router,
        route: ActivatedRoute,
        flashMessage: FlashMessagesService,
        settingsService: SettingsService
      ) {
        super(supplierService, router, route, flashMessage, settingsService);
      }

Это edit-company.component.ts

@Component({
   selector: 'edit-company',
   templateUrl: './edit-company.component.html',
   providers: [
      {
       provide: CompanyService, 
       useClass: ClientService,
       useValue: 'client', 
      },
      {
        provide: CompanyService,
        useClass: SuplierService,
        useValue: 'supplier', 
      }

  ] 
})

export class EditCompanyComponent implements OnInit {

  id: string;
  company: Company = {
    firstName: '',
    lastName: '',
    email: '',
    phone: '',
    balance: 0
  };
  hasBalance: boolean = false;
  showBalanceUpdateInput: boolean;
  parent: string;
  //service: string;
  @ViewChild('editclientForm') form: any;


  //getCompany(id: string): Observable<Company>;
  //updateCompany(company: Company): any;


  constructor(
    private companyService: CompanyService,
    private router: Router,
    private route: ActivatedRoute, 
    private flashMessage: FlashMessagesService,
    private settingsService: SettingsService 
  ) { }



  ngOnInit(): void {
    this.id = this.route.snapshot.params['id'];
    this.companyService.getCompany(this.id).subscribe(client => {
      this.company = client;
      this.id = this.company.id;
    });
    this.showBalanceUpdateInput = this.settingsService.getSettings().showBalanceUpdateInput;
  }


  onSubmit({value, valid}: {value: Company, valid: boolean}){
    if(!valid){
      this.flashMessage.show('Please, fill out the form correctly', {
        CssClass: 'alert-danger', timeout: 4000
      });
    } else {
      value.id = this.id;
      //this.clientService.updateCompany(value).then( () => {
      this.companyService.updateCompany(value).then( () => {
        this.flashMessage.show('Client updated successfuly', {
          cssClass: "alert-success", timeout: 4000
        });
      }, ()=>{
        this.flashMessage.show('Client could not be updated. Try again later.', {
          cssClass: 'alert-danger', timeout: 4000
        });
      });
      this.router.navigate([`/${this.parent}/${this.id}`]);
    }
  }
}

ОШИБКА TypeError: this. companyService.getCompany не является функцией в EditCompanyComponent.ngOnInit (edit-company.component.ts: 62) в callHook (core. js: 3937) в callHooks (core. js: 3901) в executeInitAndCheckHooks (core. js: 3842) в refreshView (core. js: 11795) в refreshComponent (core. js: 13217) в refreshChildComponents (core. js: 11508) в refreshView (core. js: 11829) в refreshDynamicEmbeddedViews (core. js: 13142) в refreshView (core. js: 11800)

Кто-нибудь знает, как сделать это правильно? Заранее спасибо.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...