Angular 5在第一次编译时出错(错误:TS2339),但成功编译后一切正常

时间:2018-03-16 10:41:59

标签: javascript angular typescript angular5

我写的不是典型的案例代码,我从API服务器获取了一些信息,但不知道,如何查看所有响应字段。得到回应后,我应该创建表单来更新这个并发回。 因为我不知道所有ngModel,所以我会在响应后动态生成一些字段,并在模板中将其分配给ngModel。 在下次第一次启动我的Angular 5应用程序后停止ng serve -o后,我收到编译错误。如果我评论问题的代码,编译,然后取消注释它 - 一切正常。

order.component.ts

import {Component, OnInit} from '@angular/core';
import {UserService} from '../user/user.service';
import {OrderService} from './order.service';
import {enumUserTypes} from '../user/user.model';
import {Router, ActivatedRoute, ParamMap} from '@angular/router';
import 'rxjs/add/operator/switchMap';
import {Order} from './order.model';
import {Observable} from 'rxjs/Observable';

@Component({
  selector: 'app-order',
  templateUrl: './order.component.html',
  styleUrls: ['./order.component.scss']
})
export class OrderComponent implements OnInit {
  orderContent = [];
  edit: boolean;
  userTypes = enumUserTypes;

  constructor(
    private route: ActivatedRoute,
    private router: Router,
    public userService: UserService,
    public orderService: OrderService
  ) {
  }

  ngOnInit() {
    this.route.paramMap
      .switchMap((params: ParamMap) =>
        this.orderService.getOrder(params.get('orderId'))).subscribe(response => {
      this.orderService.order = response;
    });
    this.edit = false;
  }


  editOrder() {
    for (let item in this.orderService.order.orderContent) {
      if (this.orderService.order.orderContent.hasOwnProperty(item)) {
        let newClassFieldName: string = this.orderService.order.orderContent[item].className;
        let newClassFieldLabel: string = this.orderService.order.orderContent[item].label;
        let newClassFieldValue: string = this.orderService.order.orderContent[item].value;
        this[newClassFieldName] = {
          className: newClassFieldName as string,
          label: newClassFieldLabel as string,
          value: newClassFieldValue as string
        };
        this.orderContent.push({
          className: this[newClassFieldName].className,
          label: this[newClassFieldName].label,
          value: this[newClassFieldName].value
        });
      }
    }
    this.edit = true;
  }

  submit() {
    this.orderContent = [];
    for (let item in this) {
      if (this.hasOwnProperty(item) &&
        item.substring(0, 17) === 'orderContentField') {
        this.orderContent.push({
// error TS2339: Property 'className' does not exist on type 'this[keyof this]'.
          className: this[item].className,
// error TS2339: Property 'label' does not exist on type 'this[keyof this]'.
          label: this[item].label,
//  error TS2339: Property 'value' does not exist on type 'this[keyof this]'.
          value: this[item].value
        });
      }
    }
    this.orderService.order.orderDataUpdate = new Date();
    this.orderService.updateOrder(
      this.userService.user.userId,
      this.orderService.order.orderName,
      this.orderService.order.orderCost,
      this.orderContent).subscribe(response => {
    });
  }

  saveEditsOrder() {
    this.edit = false;
  }

}

order.component.html

<div *ngIf="this.edit" class="wrapper--order--edit-form">
  <form class="form" #OrderEditPageForm="ngForm" novalidate>
    <ng-container *ngFor="let item of this.orderService.order.orderContent">
      <label class="label" for="{{item.className}}">{{item.label}}</label>
      <input class="input"
             [(ngModel)]="this[item.className].value"
             id="{{item.className}}"
             name="{{item.className}}"/>
    </ng-container>
    <button class="btn"
            type="submit"
            role="button"
            (click)="submit()">
      Send
    </button>
  </form>

order.service.ts

import {Injectable} from '@angular/core';
import {Order} from './order.model';
import {Router} from '@angular/router';
import {HttpClient} from '@angular/common/http';
import {UserService} from '../user/user.service';
import {Observable} from 'rxjs/Observable';
import {apiRoutes} from '../app.config';

@Injectable()
export class OrderService {
  order: Order = new Order();

  constructor(private router: Router,
              private httpClient: HttpClient,
              public userService: UserService) {
  }


  createOrder(userId: number, orderName: string, orderCost: number, orderContent: any): Observable<Order> {
    return this.httpClient.post<Order>(apiRoutes.orders,
      {
        userId: userId,
        orderName: orderName,
        orderCost: orderCost,
        isOrderOpen: this.order.isOrderOpen,
        isOrderPaidOf: this.order.isOrderPaidOf,
        orderWorkStatus: this.order.orderWorkStatus,
        orderPaymentStatus: this.order.orderPaymentStatus,
        orderDataOpened: this.order.orderDataOpened,
        orderDataUpdate: this.order.orderDataUpdate,
        orderDataClosed: this.order.orderDataClosed,
        orderDataPayment: this.order.orderDataPayment,
        conversationId: this.order.conversationId,
        orderContent: orderContent
      });
  }

  updateOrder(userId: number, orderName: string, orderCost: number, orderContent: any): Observable<Order> {
    return this.httpClient.put<Order>(apiRoutes.order + this.order._id,
      {
        userId: userId,
        orderName: orderName,
        orderCost: orderCost,
        isOrderOpen: this.order.isOrderOpen,
        isOrderPaidOf: this.order.isOrderPaidOf,
        orderWorkStatus: this.order.orderWorkStatus,
        orderPaymentStatus: this.order.orderPaymentStatus,
        orderDataOpened: this.order.orderDataOpened,
        orderDataUpdate: this.order.orderDataUpdate,
        orderDataClosed: this.order.orderDataClosed,
        orderDataPayment: this.order.orderDataPayment,
        conversationId: this.order.conversationId,
        orderContent: orderContent
      });
  }

  getUserOrders(): Observable<Order> {
    return this.httpClient.post<Order>(apiRoutes.userOrders, {userEmail: this.userService.user.userEmail});
  }

  getOrder(id: string): Observable<Order> {
    return this.httpClient.get<Order>(apiRoutes.order + id);
  }

}

order.model.ts

export class Order {
  constructor(
    public _id: number = null,
    public userId: number = null,
    public orderName: string = '',
    public orderCost: number = null,
    public isOrderOpen: boolean = true,
    public isOrderPaidOf: boolean = false,
    public orderWorkStatus: string = 'Checking documents',
    public orderPaymentStatus: string = 'Not paid',
    public orderDataOpened: Date = new Date(),
    public orderDataUpdate: Date = null,
    public orderDataClosed: Date = null,
    public orderDataPayment: Date = null,
    public conversationId: number = null,
    public orderContent: Object = []
  ) {
  }
}

在获取响应API后,我在创建新字段时遇到了一些错误。

Errors TS2339: Property 'className' does not exist on type 'this[keyof this]'.

Error TS2339: Property 'label' does not exist on type 'this[keyof this]'.

Error TS2339: Property 'value' does not exist on type 'this[keyof this]'.

我该如何解决这个问题? 我应该关闭这个检查编译器或重新格式化我的代码?

1 个答案:

答案 0 :(得分:1)

这是你的错误:

editOrder() {
  /* ... */
  this.orderContent.push({
    className: this[newClassFieldName].className,
    label: this[newClassFieldName].label,
    value: this[newClassFieldName].value
  });
}

更确切地说:

this[newClassFieldName].className

当你写这篇文章时,你会尝试阅读OrderComponent中的变量。

这可能有效,因为您之前声明了该变量。但是你的问题是你在变量中创建了变量,这些变量有很奇怪的名字。该错误告诉您:

Property 'className' does not exist on type 'this[keyof this]'

你声明这个变量

let newClassFieldName: string = this.orderService.order.orderContent[item].className;

就在那之前,你能写吗

console.log(this.orderService.order.orderContent[item].className);

告诉我结果?