【问题标题】:Problem with calling export class in angular 8在角度 8 中调用导出类的问题
【发布时间】:2019-11-16 15:19:01
【问题描述】:

我正在使用 Angular 做一个新的应用程序。我目前正在使用 Angular 8。这是我的问题。

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

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

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

我在下面的代码 sn-p 上有错误:

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

}

【问题讨论】:

    标签: angular typescript


    【解决方案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 {
    ....
    }
    

    希望这会有所帮助。

    【讨论】:

    • 在 this.service.getClient().subscribe(result : Client => 上添加“客户端”给我这个找不到名称“结果”。
    • 它也给了我这个错误。 src/app/client/client.component.ts:75:46 中的错误 - 错误 TS1005: ',' 预期。 75 this.service.getClient().subscribe(result: Client => {
    • 将客户端添加到结果只会给它一个数据类型。所以结果应该仍然可以访问。你可以在 stackblitz 中提供一个示例吗?
    • 这里是编辑stackblitz.com/edit/angular-4g4wtb。我刚刚在 src/app 文件夹下创建了客户端和共享文件夹以及与问题相关的文件
    • @DevGeek 请确保创建的 stackblitz 在您的本地计算机上进行了类似的正确配置。不只是复制粘贴代码
    猜你喜欢
    • 1970-01-01
    • 2021-02-25
    • 2021-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多