liveBook · Manning

Shared resource

As explained in Pro Angular 16

A shared object is an object instance made available to multiple application components so they can access common state or behavior.

A shared resource is an object instance made available to multiple components, allowing them to use common state and behavior. One component can edit the shared value while another displays it. section 18.2.1

Shared discount state

Create one DiscountService instance in ProductTableComponent. Pass it to PaDiscountEditorComponent and PaDiscountDisplayComponent through the discounter input. The editor changes discounter.discount with two-way binding, while the display reads the same property. The service also centralizes discount behavior with getters, a setter, and applyDiscount, which prevents prices from falling below $5. section 18.2.1

Listing 18.2. The contents of the discount.service.ts file in the src/app folder
export class DiscountService {
    private discountValue: number = 10;
 
    public get discount(): number {
        return this.discountValue;
    }
 
    public set discount(newValue: number) {
        this.discountValue = newValue ?? 0;
    }         
 
    public applyDiscount(price: number) {
        return Math.max(price - this.discountValue, 5);
    }
}

Inspect the complete DiscountService implementation, including its private state, discount accessors, and price-adjustment method. section 18.2.1

How Pro Angular 16 covers it

How deep it goes
Explains object creation, input passing, getters, setters, and two-way binding, but stops short of service injection.
Examples
Uses DiscountService, a discount editor, a discount display, and a product-table template.
What it assumes
Assumes Angular components and templates while demonstrating shared objects through a concrete product example.
What you can do after
Build shared component state by creating one object and passing it through Angular input properties.
How it connects
Connects components through input properties, data binding, two-way binding, and services.

Also explained in

Compare how 3 books explain shared resource →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Pro Angular 16. The section links point to the parts of the book it draws on.