我开始在 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;
}
篮子后端服务
GetBasket() {
return this.authHttp.get(this.apiUrl + 'api/GetBasketByUser?id=' + parseInt(this.decodedJwt['userId']), { headers: contentHeaders });
}
篮子服务
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 来更新几个组件,但不确定这是否是最好的解决方案!