Passing data from service to Component --> Child Components

后端 未结 2 1420
甜味超标
甜味超标 2021-01-22 17:17

To be very short i am using this Plunker I have a scenario where i have to create controls dynamically by reading the elements data from a service. So when i read the data from

2条回答
  •  闹比i
    闹比i (楼主)
    2021-01-22 17:47

    I'm not sure that I have understand your problem but when I need to pass data from service to a component I use subscription in this way.

    Two component (a parent component and its children or other different component) can share a service whose interface enables bi-directional communication.

    Like in the Observer pattern, in this case the scope of the service instance is the notification from a component (Publisher) and other componentents (Subscriber).

    mycomponent.service.ts

    import { Injectable } from '@angular/core';
    import { Subject } from 'rxjs/Subject';
    
    @Injectable()
    export class MyComponentService{
        // Observable 
        private sampleObservable = new Subject();
        // Observable boolean streams
        sampleSubscriber = this.sampleObservable.asObservable();
        // Event for notification from publisher to subscriber
        sampleEventChanged(value:boolean)
        {
            this.sampleObservable.next();
        }
    }
    

    In the component who wants to notify all subscribers a change of its state:

    mycomponent-publisher.ts

    import { Component } from '@angular/core';
    import { MyService } from './mycomponent.service';
    
    @Component({
      selector: 'app-my-control-publisher',
      template: `
      

    This is the publisher control

    `, providers: [MyService] }) export class MyControlPublisherComponent { constructor(private myService: MyService) { } announce() { this.myService.sampleEventChanged(true); } }

    In the subscriber component who want to get the notification.

    mycomponent-subscriber.ts

    import { Component, OnDestroy } from '@angular/core';
    import { MyService } from './mycomponent.service';
    import { Subscription } from 'rxjs/Subscription';
    
    @Component({
     selector: 'app-my-control-subscriber',
     template: `
     

    This is the subscriber control

    `, }) export class MyControlSubscriberComponent { // Subscriptions private componentSubscription: Subscription; constructor(private myService: MyService) { // Subscription of the notifications this.componentSubscription= this.myService.sampleSubscriber.subscribe(value => { // Put the code for manage the notification here } } ngOnDestroy() { // Release subscription to avoid memory leaks when the component is destroyed this.componentSubscription.unsubscribe(); } }

    I hope that this can help you.

提交回复
热议问题