我开始在Rxjs中使用BehaviorSubject,在这方面经验有限。到目前为止,我能够获取组件中的根级参数,但访问嵌套对象会导致“无法读取未定义的属性x”。
类:
export class Basket extends X23Object {
public BasketId: number;
public UserID: number;
public User: User;
public BasketLines: BasketLine[] = [];
}
export class BasketLine extends X23Object {
public BasketLineId: number;
public BasketId: number;
public ProductId: number;
public Quantity: number;
public Product: Product;
public Price: number;
public Name: string;
}
export class Product extends X23Object {
public ProductId: number;
public CategoryId: number;
public Name: string;
public Code: string;
public Price: number;
public Details: string;
public Images: Image[];
public Category: Category;
}
BasketBackendService
GetBasket() {
return this.authHttp.get(this.apiUrl + 'api/GetBasketByUser?id=' + parseInt(this.decodedJwt['userId']), { headers: contentHeaders });
}
BasketService
private _lines: BehaviorSubject<BasketLine[]> = new BehaviorSubject([new BasketLine]);
get getLines() {
return this._lines.asObservable();
}
loadBasket() {
this.basketBackendService.GetBasket()
.subscribe(
response => {
let lines = <BasketLine[]>response.json().basket.BasketLines;
this._lines.next(lines);
},
error => console.log(error.text())
);
}
模板(摘录)
<tr *ngFor="let line of basketService.getLines | async">
<td><img class="login-logo" src="{{ line.Product.Images[0].ThumbUrl }}" width="100%" /></td>
<td><a [routerLink]="['Product', { id: line.ProductId }]"> {{ line.Product.Code }} </a></td>
<td><a [routerLink]="['Product', { id: line.ProductId }]">{{ line.Product.Name }}</a></td>
<td class="text-right">{{ line.Price | currency:'GBP':true:'.2-2' }}</td>
<td class="text-center">{{ line.Quantity }}</td>
<td class="text-right">{{ line.Quantity * line.Price | currency:'GBP':true:'.2-2' }}</td>
<td><button (click)="DeleteLine(line.BasketLineId)">Remove</button></td>
</tr>
如果删除深层嵌套对象的引用,我会返回预期的结果。
我正在尝试使用BehaviorSubject来更新多个组件,但不确定这是否是最佳解决方案!
答案 0 :(得分:0)
代码对我来说很好,我想通过“深嵌套”你的意思是例如line.Product.Code
。如果它适用于line.Quantity
,则问题很可能不在BehaviorSubject
中,而在于数据结构中。
我不知道您的特定用例是什么,但您根本不需要同时使用BehaviorSubject
或async
管道。
对于BasketService
,您只能使用:
export class BasketService {
lines: BasketLine[];
// ...
loadBasket() {
this.basketBackendService.GetBasket().subscribe(
response => {
this.lines = <BasketLine[]>response.json().basket.BasketLines;
},
error => console.log(error.text())
);
}
}
然后只用:
渲染它<tr *ngFor="let line of basketService.lines">
// ...
</tr>