将JSON数据从应用程序组件传递到Angular 6中的另一个组件

将JSON数据从应用程序组件传递到Angular 6中的另一个组件,json,angular,components,angular6,Json,Angular,Components,Angular6,我有两个部分, 1.应用程序组件 2.主要成分 app.component.ts ngOnInit () { this.httpService.get('./assets/batch_json_data.json').subscribe(data => { this.batchJson = data as string []; } import { Component, OnInit, ViewChild, Input } from

我有两个部分, 1.应用程序组件 2.主要成分

app.component.ts

  ngOnInit () {
      this.httpService.get('./assets/batch_json_data.json').subscribe(data => {
         this.batchJson = data as string [];    
       }
import { Component, OnInit, ViewChild, Input } from '@angular/core';
import { AppComponent } from '../app.component';

export class MainComponent implements OnInit {
}
constructor(private _appComponent : AppComponent )

ngOnInit(){
  this._appComponent.batchJson$.subscribe((data)=>{
   if(data != null){
    //set data to local variable here
  }  
 })
}
我能够将JSON从文件中获取到“batchJson”,并需要将其传递到我的主组件以进行进一步的操作

没有任何事件或任何东西触发此事件

我还没有实现任何东西,我正在尝试阅读@Input、@Output等,但不了解它是如何工作的,需要进一步了解它

我刚刚在main.component.ts中声明了basics

  ngOnInit () {
      this.httpService.get('./assets/batch_json_data.json').subscribe(data => {
         this.batchJson = data as string [];    
       }
import { Component, OnInit, ViewChild, Input } from '@angular/core';
import { AppComponent } from '../app.component';

export class MainComponent implements OnInit {
}
constructor(private _appComponent : AppComponent )

ngOnInit(){
  this._appComponent.batchJson$.subscribe((data)=>{
   if(data != null){
    //set data to local variable here
  }  
 })
}

请帮帮我,我在Angular方面是一个绝对的新手,我不能尝试任何东西,因为我的概念不清楚,我确实浏览了Stack Overflow,答案与我的要求不符。

您可以实现执行所有相关http操作的公共服务,您可以将此服务注入任何您想要的组件并读取json

确保返回http.get并在调用此方法的任何位置订阅它


如果您不了解服务,可以阅读angular中有关创建和注入服务的内容

一种解决方案可能是在app.component.ts中使用公共行为主体

public batchJson$ = new BehaviorSubject<JSON>(null);
   ngOnInit () {
      this.httpService.get('./assets/batch_json_data.json').subscribe(data => {
         this.batchJson = data as string [];  
         this.batchJson$.next(JSON.parse(data));
       }

通常我将这种逻辑存储在服务中,在组件中使用这种逻辑肯定会为您指明学习这一概念的正确方向。最好您的组件负责与UI交互并呈现数据,而您的服务负责检索和分发数据。

您可以使用rxjs subject通过应用程序发送数据,并使用subject.getValue()将数据提取到任何地方方法。

首先,在开始研究任何技术之前,你应该抽出时间来理解它的概念。否则,你将花费大部分时间寻求帮助

我已经在这里创建了演示-。我希望它能帮助你