且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

组件值更改后,角度视图未更新

更新时间:2022-02-07 22:33:43

这似乎非常适合可观察数据服务

This seems like a good fit for an observable data service

interface Item {
    id: number;
    name:string;
    price:number;
}

@Injectable()
export class Cart {
    private _items: BehaviorSubject<List<Item>> = new BehaviorSubject(List());

    public items: Observable<Item[]> = this._items.asObservable();

    addItem(newItem:Item):Observable{
         this._items.next(this._items.getValue().push(newItem));
    }
}

然后你可以像这样在组件内部使用 Cart

Then you can consume the Cart either inside the component like this

@Component({
    selector: 'app-cart-counter',
    template: `
        <div>Count: {{items.length}}</div>
    `
})
export class CartCounterComponent implements OnInit {
    items: Item[];

    constructor(
        private cart: Cart
    ) {}

    ngOnInit(){
        this.cart.items.subscribe(items => this.items = items;)
    }
}

或者像这样直接在模板中使用observable

Or use the observable directly in the template like this

@Component({
    selector: 'app-cart-counter',
    template: `
        <div>Count: {{(cart.items | async).length}}</div>
    `
})
export class CartCounterComponent{
    constructor(
        private cart: Cart
    ) {}
}

有关组件交互的更多信息可以在此处的文档中找到:https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service

More information on component interaction can be found in the docs here: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service

可以在此处找到有关可观察数据服务模式的更多信息:http://blog.angular-university.io/how-to-build-angular2-apps-using-rxjs-observable-data-services-pitfalls-to-avoid/

More can be found on the Observable Data Service pattern here: http://blog.angular-university.io/how-to-build-angular2-apps-using-rxjs-observable-data-services-pitfalls-to-avoid/