1

我开始在 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 来更新几个组件,但不确定这是否是最好的解决方案!

4

1 回答 1

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>
于 2016-08-15T16:01:48.347 回答