我正在进行Angular Material类的分配,在其中列出了一组带有价格的维修服务。用户可以检查所需的服务。用户单击“计算”,然后会打开一个发票窗口,其中仅列出他们选择的服务和总计。我可以显示我的列表,但是在获取已检查的服务时遇到了麻烦。我在服务中使用Observable填充了第一个列表。然后,我尝试使用管道和过滤器抓取选中的项目。但是在我的过滤器中,我收到“类型为Fix []的属性检查不存在”错误。有人可以帮忙吗?
代码如下:
fix.ts
export interface Fix {
id: number;
name: string;
price: string;
checked: boolean;
}
fix.service.ts
import { Observable, of } from 'rxjs';
import { Injectable } from '@angular/core';
import { Fix } from './fix';
@Injectable()
export class FixService {
fixes: Fix[] = [
{id: 1, name: "Password Reset", price: "39.99", checked: false},
{id: 2, name: "Spyware Removal", price: "99.99", checked: false},
{id: 3, name: "RAM Upgrade", price: "129.99", checked: false},
{id: 4, name: "Software Installation", price: "49.99", checked: false},
{id: 5, name: "Tune-up", price: "89.99", checked: false},
{id: 6, name: "Keyboard Cleaning", price: "45.00", checked: false},
{id: 7, name: "Disk Clean-up", price: "149.99", checked: false},
];
constructor() { }
getFix(): Observable<Fix[]> {
return of(this.fixes);
}
}
base-layout.component.html
<div class="wrapper">
<mat-card class="services-panel frm-services-panel">
<mat-card-header class="frm-services-header">
<mat-toolbar class="frm-services-toolbar">
Available Services
</mat-toolbar>
</mat-card-header>
<mat-card-content class="frm-services-body">
<mat-form-field class="frm-services-formfield">
<mat-checkbox *ngFor="let fix of fixes | async" value="{{fix.name}} {{fix.price}}" [(ngModel)]="fix.checked">
<div fxLayout="row">
<div class="frm-services-name">
{{ fix.name }}
</div>
<div class="rightSide">
{{ fix.price }}
</div>
</div>
</mat-checkbox>
</mat-form-field>
</mat-card-content>
<mat-card-actions class="frm-login-actions">
<button mat-raised-button class="btn-login button1" (click)="getCheckboxes()">Calculate</button>
</mat-card-actions>
</mat-card>
</div>
base-layout.component.ts
import { Observable } from 'rxjs';
import { Component, OnInit } from '@angular/core';
import { filter, map } from 'rxjs/operators';
import { Fix } from '../fix';
import { FixService } from '../fix.service';
@Component({
selector: 'app-base-layout',
templateUrl: './base-layout.component.html',
styleUrls: ['./base-layout.component.scss'],
providers: [FixService]
})
export class BaseLayoutComponent implements OnInit {
fixes: Observable<Fix[]>;
constructor(private fixService: FixService) { }
ngOnInit() {
this.fixes = this.fixService.getFix();
}
get getCheckboxes() {
return this.fixes
.pipe(
filter(f => f.checked == true),
map(f => f.values));
}
}
答案 0 :(得分:1)
通过使用模板中的异步管道,该类无法访问可观察对象的返回值。异步管道的好处是避免必须手动订阅可观察对象。但是,如果您需要访问该类中的值,则需要手动预订表示可观察的值。 (请记住要取消订阅ngOnDestroy)
我在这里进行了快速堆叠-> quick sample。选择修复程序,然后单击“计算”,您会看到所选选项的列表
如果您真的不想手动订阅,则可以对过程进行更改,以将当前选择的更改补丁传递给输入框,但这似乎是很多额外的工作,只是为了避免手动订阅
理想情况下,我建议使用formGroup轻松访问控件的状态。