确定。我试图添加一些方法来模拟一个对象的模型类,该对象是可观察的流,我希望例如将两个propoerties相乘并将结果返回到该新属性中。当通过异步管道显示数据流时,这是有效的,但是如何使用正常订阅的observable执行此操作?我试图通过异步返回getter - 等待但是没有工作
export interface IProduct {
price: number;
tax: string;
}
export class Product implements IProduct {
constructor(
public price: number,
public tax: string,
) { }
get grossPrice() {
return this.price * parseInt(this.tax)
}
}
export class ProductService {
private url = ''
constructor(private http: HttpClient){ }
getAll(): Observable<Product[]> {
return this.http.get<Product[]>(this.url)
}
}
@Component({
template: `<div *ngFor="let product of products">
{{ product.grossPrice }}
</div>
`
})
export class ProductsViewComponent implements OnInit, OnDestroy {
products: Product[] = [];
constructor(private productService: ProductService){}
this.productService
.getAll()
.subscribe(data => this.products = data)
}
答案 0 :(得分:1)
这是将编译的代码。你需要修改几个。
IProduct
调用中返回的HttpClient
转换为类实例Product
。这是使用Pipeable Operators完成的,另请参阅so - In Angular rxjs when should I use pipe vs map。ngOnInit
,而不是组件的构造函数中调用该服务。subscribe
。<强> ProductService.ts 强>
import { Observable } from 'rxjs/observable';
import { map } from 'rxjs/operators/map';
import { HttpClient } from '@angular/common/http';
export interface IProduct {
price: number;
tax: string;
}
export class Product implements IProduct {
constructor(public price: number, public tax: string) {
}
get grossPrice() {
return this.price * parseInt(this.tax);
}
}
export class ProductService {
private url = '';
constructor(private http: HttpClient) { }
getAll(): Observable<Product[]> {
return this.http.get<IProduct[]>(this.url)
.pipe(map((products) => {
return products.map(p => new Product(p.price, p.tax));
}));
}
}
<强> ProductsViewComponent.ts 强>
订阅observable并将结果分配给字段的组件。
import { Component, OnInit } from '@angular/core';
import { Product, ProductService } from './ProductService;
@Component({
template: `<div *ngFor="let product of products">
{{ product.grossPrice }}
</div>`
})
export class ProductsViewComponent implements OnInit {
products: Product[] = [];
constructor(private productService: ProductService) { }
ngOnInit() {
this.productService
.getAll()
.subscribe(data => this.products = data);
}
}
<强> ProductsViewAsyncPipeComponent.ts 强>
使用异步管道的组件。
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs/observable';
import { Product, ProductService } from './ProductService;
@Component({
template: `<div *ngFor="let product of products | async">
{{ product.grossPrice }}
</div>`
})
export class ProductsViewAsyncPipeComponent implements OnInit {
products: Observable<Product[]>;
constructor(private productService: ProductService) { }
ngOnInit() {
this.products = this.productService.getAll();
}
}