简体   繁体   中英

How to share the http response between two components in angular 6?

I have a component named modal. In this model ts file, Im making a http request to get json data from node js. After retrieving Im just displaying it in a table format. My table structre is like below.

modalId   modalName  subModal  AddSubmodal
111        modal1                add      
112        modal2                add

The problem here is after clicking the add button, one pop up box will come(Another component) asking us to enter sub model name. There we should display the modal name for which we have to enter sub model details.

So After clicking the add button, I need to pass the modalId to fetch the model details. So here I need to pass the modalID dynamically to the addmodel(second) component. Can anybody tell me how to do this?

My modal.component.ts:

 @Component({
selector: 'app-modal',
templateUrl: './modal.component.html',
styleUrls: ['./modal.component.css']
})
 export class ModalComponent extends Lifecycle {
 public d: any;
 constructor(
    private $modal: $ModalManagerService,
    private http: HttpClient,
) {
    super();
}
 _initialize(): void {          
   this.http.get('/getModel',{responseType:"json"}).subscribe(
   response => {
       this.data = response;
        var sample=JSON.stringify(response);
      });
    }
addSubmodal(modalId){
 let obj = this.$modal.show(AddSubModalComponent)
        .subscribe(r => {
            obj.unsubscribe();
        });

};

My modal html:

 <table class="table table-bordered" >
    <thead>
      <tr>
        <th>modal ID</th>
        <th>modal Name</th>
        <th>SubModal</th>
        <th>AddSubmodal</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let i of d">
        <td>{{ i.Record.modalId }}</td>
        <td>{{ i.Record.modalName }}</td>
        <td></td>
        <td>
          <img src="./../Add_Icon.svg" (click)="addSubmodal(i.Record.modalId);">
        </td>
      </tr>
    </tbody>
  </table>

As I'm new to angular, Im just browsing angular answers in stackoverflow & doing it. Please tell me how to achieve this in my second component html file?

Use Input & Output Decorators

Basic concept ---> DEMO

app.component.html:

<app-component1 (elm)="catch1Data($event)">

</app-component1>
<app-component2 [elm]="datatocomp2" *ngIf="datatocomp2"></app-component2>

parent component : {{datatocomp2 | json}}

app.component.ts:

 datatocomp2: any;

  catch1Data(data) {
    console.log(data)
    this.datatocomp2 = data;
  }

component1.ts:

@Output () elm : EventEmitter<any> = new EventEmitter<any>();



objectData: any;

  constructor() { }



 ngOnInit() {
    let objectData = {
      comp: 'component 1',
      data: 'anything'
    }

this.objectData = objectData;
this.elm.emit(objectData)
  }

component2.ts:

@Input() elm: any;

  constructor() { }

  ngOnInit() {
    console.log(this.elm);
  }

Use a shared service to share data between components, event emitter method isn't the best way for components in routing

Simple example , create a datashare service

//DataShare Service

import { ReplaySubject } from 'rxjs/Rx';

export class DatashareService {

    private dataObs$ = new ReplaySubject<any>(1);

    getData() {
        return this.dataObs$.asObservable();
    }

    updateData(data) {
        this.dataObs$.next(data);
    }

    constructor() { }
}

In the component where you fetch data,

import { DatashareService } from '../datashare.service';

update the value of the observable

this.dataService.updateData(this.modal_id);

Subscribe to the observable from the sub components

import { Component, OnInit,OnDestroy,NgZone } from '@angular/core';
import { DatashareService } from '../datashare.service';
import { Subscription } from 'rxjs/Subscription';

In the constructor,

 constructor(private dataService: DatashareService
  ,private zone:NgZone){}

Now, access data on init,

 ngOnInit() {


        this.subscription.add(this.dataService.getData().subscribe(data => { 
           this.zone.run(()=>{
               console.log(data);
               this.modal_selected=data;

            })

        }))

             }

Don't forget to unsubscribe on destroy

 ngOnDestroy() {
        // unsubscribe to ensure no memory leaks
        this.subscription.unsubscribe();

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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