简体   繁体   English

两个子组件之间的更改检测

[英]Change detection between two child components

I have the following parent component: 我有以下父组件:

export class CheckoutComponent implements OnInit {

    public customer: Customer;
    public items: Array<Item>;

    constructor(private sharingDataService: SharingDataService) { }

    ngOnInit(): void {
        this.sharingDataService.setCustomer(this.initializeCustomer());
        this.sharingDataService.setItems(this.initiatlizeItems());
        this.customer = this.sharingDataService.getCustomer();
        this.items = this.sharingDataService.getItems();
    }
    ......
}

with the following html: 使用以下html:

<div>
    <app-shipping-option></app-shipping-option>
    <app-review></app-review>
</div>

the first child "app-shipping-option" : 第一个子代“ app-shipping-option”

export class ShippingOptionComponent implements OnInit {

    public options: Array<Option> = [];

    constructor(private sharingDataService: SharingDataService) { }

    ngOnInit(): void {
        this.initializeOptions();
    }

    private initializeOptions(): void {
        let option1: Option = {
            name: 'Free',
            price: 0
        };
        let option2: Option = {
            name: 'Paid',
            price: 15
        };
        this.options.push(option1, option2);
    }

    private createCustomerForm(): void {
        this.shippingOptionForm = this.formBuilder.group({
            option: [this.options[0], Validators.required]
        });
    }

    chooseOption(option): void {
        this.sharingDataService.setShippingOption(option);
    }
}

and here the second child "review" : 这里是第二个孩子的“评论”

export class ReviewComponent implements OnInit {

    constructor(private sharingDataService: SharingDataService) { }

    ngOnInit(): void {
        console.log(this.sharingDataService.getShippingOption())
    }
}

I want to detect change in the second child so when i change an option on the first child , the second child should print this option on console. 我想检测第二个孩子的更改,因此当我更改第一个孩子的选项时,第二个孩子应在控制台上打印此选项。 But with the code above it print the first provided option on init. 但是上面的代码会在init上打印第一个提供的选项。 those child of cours are shown on the same page and the ngOnInit are called on page load. 这些ngOnInit子项显示在同一页面上,并在页面加载时调用ngOnInit

here's the service used to share data between components: 这是用于在组件之间共享数据的服务:

@Injectable()
export class SharingDataService {

    private data: InputDetails = new InputDetails();

    constructor() { }

    setShippingOption(shippingOption): void {
        this.data.shippingOption = shippingOption;
    }

    getShippingOption(): { name: string, price: number } {
        return this.data.shippingOption;
    }
}
    You can use Subject type of an observable to achieve this. 

    Here is how to use it:

    In Service File: Create the Subject

    import { Subject } from 'rxjs/internal/Subject';

    export class SharingDataService {
      public abcObservable = new Subject<object>();
    }

    In Child1: import the Service within the constructor and use the .next() to emit values whenever you see a change in options on this child

import { SharingDataService } from ....;

export class ShippingOptionComponent implements OnInit {

    public options: Array<Option> = [];

    constructor(private sharingDataService: SharingDataService) { }

    chooseOption(option): void {
        this.sharingDataService.abcObservable.next(option);
    }

}

In Child2: Subscribe to this Subject

export class ReviewComponent implements OnInit {

    constructor(private sharingDataService: SharingDataService) { }

    ngOnInit(): void {

        this.sharinDataService.abcObservable.subscribe(

      (data) =>  console.log("Call your next methods from here!"),
      (error) => console.log("When there is an error in the observable, it comes here", error),
      () => console.log("If the subject completes sending all values, it comes in here")
    );
    }
}

More details aout how to share data between different components can be read here: https://angularfirebase.com/lessons/sharing-data-between-angular-components-four-methods/

您可以使用rxjs中的Subject Class,这是如何进行某种通知的示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM