如何正确地从一个对象中获取一个值并将其添加到另一个值中。角度的

时间:2019-07-06 15:07:00

标签: angular typescript object

我是Angular的新手,并尝试创建出租车预订应用程序。 到目前为止,一切都按预期工作,但是我必须实现基于车辆价格和tarif的价格计算器,以便双向绑定{{price}}向用户显示正确的金额

车辆的类型为数字(0,5,20),但是tarif是json-object     zipValue = {view:'1010-Innere Stadt',值:24}

到目前为止,我的解决方案是用Vehicle填充变量并添加object.value

price = this.zipValue.value + this.price

Angular向我抛出一个错误,即类型'object'上不存在Property'value'

如何正确计算此值而没有错误?

示例代码: app-component.html

<form (ngSubmit)="onSubmit(form)" #form="ngForm">

<mat-form-field>
  <mat-label>Passagiere</mat-label>
    <mat-select name="passengers" ngModel [(value)]='passengersAmount'>
      <mat-option *ngFor="let p of passengers" [value]="p.value">
            {{p.view}}
      </mat-option>
   </mat-select>
</mat-form-field>

<mat-form-field>
        <mat-label>Gepäckstücke</mat-label>
        <mat-select name="luggage" ngModel [(value)]='luggage'>
          <mat-option *ngFor="let s of pieces" [value]="s.value">
            {{s.view}}
          </mat-option>
        </mat-select>
      </mat-form-field>

<mat-select placeholder="Postleitzahl" [(ngModel)]="zipValue" name="zip">
  <mat-option *ngFor="let z of zip" [value]="z" >{{z.view}}</mat-option>
 </mat-select>

<button (click)="calculate();">name</button>
</form>

示例代码:app.component.ts

export class FormDeComponent {

  //
  // Dynamic Objects for SELECT
  //

  passengers = [
    { value: 1, view: '1 Person' },
    { value: 2, view: '2 Personen' },
    { value: 3, view: '3 Personen' },
    { value: 4, view: '4 Personen' },
    { value: 5, view: '5 Personen' }
  ];

  pieces = [
    { value: 0, view: 'Keine' },
    { value: 1, view: '1 Stück' },
    { value: 2, view: '2 Stück' },
    { value: 3, view: '3 Stück' },
    { value: 4, view: '4 Stück' },
    { value: 5, view: '5 Stück' },
];

  zip = [
    { view: '1010 - Innere Stadt', value: 24 },
    { view: '1020 - Leopoldstadt', value: 27 },
    { view: '1030 - Landstraße', value: 29 }
  ];

  mod = [0, 5, 20]

  passengersAmount: number;
  luggage: number;
  price: number;
  zipValue: object;

  calculate() {
    if (this.passengersAmount <=3 && this.luggage <= 3) { this.price = this.mod[0] }
    else if (this.passengersAmount <=4 && this.luggage <= 4) { this.price = this.mod[1] }
    else {this.price = this.mod[2]}
    this.price = this.zipValue.value + this.price; 
  }

    onSubmit(form: NgForm) {
      console.log(form.value);
    }

  }

1 个答案:

答案 0 :(得分:3)

更改此:

zipValue: object;

对此:

zipValue: {view: string, value: number};

您可以在TypeScript中将接口定义为内联类型。以上与执行以下操作相同。

interface ZipCode {
   view: string;
   value: number;
}

zip: ZipCode[] = [
  { view: '1010 - Innere Stadt', value: 24 },
  { view: '1020 - Leopoldstadt', value: 27 },
  { view: '1030 - Landstraße', value: 29 }
];

zipValue: ZipCode;

与第一种方法相比,我更喜欢第二种方法。