简体   繁体   English

如何在角度6的两个组件之间共享http响应?

[英]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. 在此模型ts文件中,Im发出http请求以从节点js获取json数据。 After retrieving Im just displaying it in a table format. 检索Im后,仅以表格格式显示它。 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. 因此,在单击添加按钮之后,我需要传递modalId来获取模型详细信息。 So here I need to pass the modalID dynamically to the addmodel(second) component. 所以在这里,我需要将modalID动态传递给addmodel(second)组件。 Can anybody tell me how to do this? 有人可以告诉我该怎么做吗?

My modal.component.ts: 我的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: 我的模态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. 由于我是新手,我只是在stackoverflow中浏览角度答案并进行操作。 Please tell me how to achieve this in my second component html file? 请在第二个html文件中告诉我如何实现此目标?

Use Input & Output Decorators 使用输入和输出装饰器

Basic concept ---> DEMO 基本概念---> 演示

app.component.html: 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: app.component.ts:

 datatocomp2: any;

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

component1.ts: 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: 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, 现在,访问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();

    }

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

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