在角度8中调用导出类的问题

时间:2019-07-06 08:16:50

标签: angular typescript

我正在做一个应用程序,并且是Angular的新功能。我目前正在使用Angular8。这是我的问题。

我有一个名为“导出类客户端”的共享模型。该模型位于文件名称为client.model.ts的src / app / shared文件夹中。下面是示例代码。

export class Client {
ClientID: number;
ClientName: string;
}

我需要将此Client类调用到src / app / client文件夹中的client.component.ts。

我在以下代码段中出现错误:

public client_: Client;

loadData() {
    this.service.getClient().subscribe(result => {
      this.client_ = result;
      console.table(result);
    }, error => console.error(error));}

url = '';
  onSelectFile(event) {
    if (event.target.files && event.target.files[0]) {
      var reader = new FileReader();

      reader.readAsDataURL(event.target.files[0]); // read file as data url

      reader.onload = (event) => { // called once readAsDataURL is completed
        this.url = event.target.result;
      }
    }
  }

下面的错误消息

chunk {main} main-es2015.js, main-es2015.js.map (main) 643 bytes [initial] [rendered]
chunk {polyfills} polyfills-es2015.js, polyfills-es2015.js.map (polyfills) 122 kB [initial] [rendered]
chunk {runtime} runtime-es2015.js, runtime-es2015.js.map (runtime) 6.09 kB [entry] [rendered]
chunk {scripts} scripts.js, scripts.js.map (scripts) 229 kB [entry] [rendered]
chunk {styles} styles-es2015.js, styles-es2015.js.map (styles) 1.15 MB [initial] [rendered]
Date: 2019-07-06T07:51:36.380Z - Hash: 976b4a15d221c24ffe40 - Time: 6641ms

ERROR in src/app/client/client.component.ts:73:7 - error TS2696: The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?
  Type 'Object' is missing the following properties from type 'Client': ClientID, ClientName, Acronym, ContactPerson1, and 16 more.

73       this.client_ = result;
         ~~~~~~~~~~~~
src/app/client/client.component.ts:132:33 - error TS2339: Property 'result' does not exist on type 'EventTarget'.

132         this.url = event.target.result;
                                ~~~~~~

下面是两个文件的完整代码。

用于Client.Model.ts文件

export class Client {

  ClientID: number;
  ClientName: string;
  Acronym: string;
  ContactPerson1: string;
  ContactEmail1: string;
  ContactNumber1: string;
  ContactPerson2: string;
  ContactEmail2: string;
  ContactNumber2: string;
  Address: string;
  StateProvince: string;
  Zip: string;
  Country: string;
  AvailElection: boolean;
  AvailSurvey: boolean;
  Logo: string;
  CopyrightText: string;
  Active: boolean;
  Modified: Date;
  LastModified: string;
}

对于Client.Component.ts文件

import { Component, OnInit, ViewChild, TemplateRef } from '@angular/core';
import { ClientService } from '../shared/client.service';
import { NgForm } from '@angular/forms';
import { Client } from '../shared/client.model';
import { BsModalService, BsModalRef } from 'ngx-bootstrap/modal';

@Component({
  selector: 'app-client',
  templateUrl: './client.component.html',
  styles: []
})

export class ClientComponent implements OnInit {

  constructor(
    private service: ClientService,
    private modalService: BsModalService
  ) { }

  public client_: Client;

  modalRef: BsModalRef;
  @ViewChild('template', {static : true}) modal: TemplateRef<any>;

  showModal(clientData: Client) {
    if (clientData != null) this.populate(clientData);
    this.modalRef = this.modalService.show(this.modal, { class: 'modal-lg' });
  }

  hideModal(id) {
    this.modalService.hide(1);
  }

  ngOnInit() {
    this.loadData();
    this.resetForm();
  }

  populate(clientData: Client) {
    this.service.formData = Object.assign({}, clientData);
  }

  resetForm(form?: NgForm) {
    if(form!=null)
      form.resetForm();
    this.service.formData = {
      ClientID: 0,
      ClientName: '',
      Acronym: '',
      ContactPerson1: '',
      ContactEmail1: '',
      ContactNumber1: '',
      ContactPerson2: '',
      ContactEmail2: '',
      ContactNumber2: '',
      Address: '',
      StateProvince: '',
      Zip: '',
      Country: '',
      AvailElection: false,
      AvailSurvey: false,
      Logo: '',
      CopyrightText: '',
      Active: false,
      Modified: null,
      LastModified: ''
    };
  }

  loadData() {
    this.service.getClient().subscribe(result => {
      this.client_ = result;
      console.table(result);
    }, error => console.error(error));
  }

  onSubmit(form: NgForm) {
    if (form.value.ClientID == 0) {
      this.insert(form);
    }
    else {
      this.update(form);
    }    
  }

  insert(form: NgForm) {
    this.service.postClient(form.value).subscribe(res => {
        this.resetForm(form);
        this.loadData();
        this.modalService.hide(1);
      },
      err => {
        console.log(err);
      }
    )
  }

  update(form: NgForm) {
    this.service.putClient(form.value).subscribe(res => {
      this.resetForm(form);
      this.loadData();
      this.modalService.hide(1);
    },
      err => {
        console.log(err);
      }
    )
  }

  delete(ClientID: number, form: NgForm) {
    this.service.deleteClient(ClientID).subscribe(res => {
      this.resetForm(form);
      this.loadData();
      this.modalService.hide(1);
    },
      err => {
        console.log(err);
      }
    )
  }

  //upload (pending)
  url = '';
  onSelectFile(event) {
    if (event.target.files && event.target.files[0]) {
      var reader = new FileReader();

      reader.readAsDataURL(event.target.files[0]); // read file as data url

      reader.onload = (event) => { // called once readAsDataURL is completed
        this.url = event.target.result;
      }
    }
  }

}

2 个答案:

答案 0 :(得分:0)

如您从错误消息中看到的那样:

getClient()函数给出了一个对象result,该对象不适合分配给Client对象

要解决这个问题

首先

console.log(result)并查看缺少哪些道具,以便您进行修复。

第二个是可选的

尝试在ES6 +中使用新功能

// Don't use
  var obj1 = { a: 0 , b: { c: 0}};
  var obj2 = Object.assign({}, obj1);

但是使用

// Use
  let obj1 = { a: 0 , b: 5};
  let obj2 = {...obj1};

最后

Client类转换为接口,并使一些不需要的道具变为可选。

答案 1 :(得分:-1)

Typescript对于数据类型非常严格,这就是为什么您会收到此错误

 The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?
  Type 'Object' is missing the following properties from type 'Client': ClientID, ClientName, Acronym, ContactPerson1, and 16 more.

Angular抱怨是因为您声明了变量public client_: Client;,并且期望该变量具有与Client类型一致的值。

您的populate功能应该是这样的

 populate(clientData: Client) {
       // don't use Object.assign(...) anymore. clientData is already a Client type
    this.service.formData = clientData;
  }

loadData应该类似于

loadData() {
    this.service.getClient().subscribe(result: Client => {
      this.client_ = result;
      console.table(result);
    }, error => console.error(error));
  }

此处的更改是您在result变量中添加了一种类型。没有这个,结果可能是任何数据类型。

最后,您需要更改返回ClientService中数据的方式,并确保您getClient变量正在返回Client数据类型,所以它应该类似于这个

getClient():Client {
....
}

希望这会有所帮助。