繁体   English   中英

如何在 Angular 6 中使用另一个组件中的一个组件数据?

[英]How to use one component data in another component in angular 6?

我有一个 component.ts 文件,它正在进行 http 调用并检索 json 数据作为响应。 我需要在另一个 component.ts 文件中使用这个响应。 谁能告诉我如何处理这个? 第一个组件.ts:

  @Component({
selector: 'app-cat',
templateUrl: './first.component.html',
styleUrls: ['./first.component.css']
 })
 export class firstComponent extends Lifecycle {
  this.http.get('/name',{responseType:"json"}).subscribe(
   response => {
        console.log("data :"+response);
        console.log("data stringify:"+JSON.stringify(response));

   });  
   }

我需要使用我的第二个组件文件的响应中的 json 内容。 谁能告诉我如何在 angular6 中进行此操作?

****为拨打电话创建单独的服务,并在该服务中创建一个方法

  public getData(): Observable<> {

        return this.http.get('/name',{responseType:"json"}).subscribe(
   response => {
        console.log("data :"+response);
        console.log("data stringify:"+JSON.stringify(response));

   }); 
     }

****在你的组件中声明服务在构造函数中 //不要忘记导入它

public jsonData:any;
constructor(private Service: Service ) {
    }
getData() {  
        this.Service.getData().subscribe(data => {  
            console.log("Data is ",data);
this.jsonData = data;
        },  
            error => console.log(error)  
        );  
    }

最后,您可以使用 jsonData 处理您的数据。

父母对孩子:通过输入共享数据

父组件.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-parent',
  template: `
    <app-child [childMessage]="parentMessage"></app-child>
  `,
  styleUrls: ['./parent.component.css']
})
export class ParentComponent{
  parentMessage = "message from parent"
  constructor() { }
}

child.component.ts

import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-child',
  template: `
      Say {{ message }}
  `,
  styleUrls: ['./child.component.css']
})
export class ChildComponent {

  @Input() childMessage: string;

  constructor() { }

}

通过 Output() 和 EventEmitter 共享数据

父组件.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-parent',
  template: `
    Message: {{message}}
    <app-child (messageEvent)="receiveMessage($event)"></app-child>
  `,
  styleUrls: ['./parent.component.css']
})
export class ParentComponent {

  constructor() { }

  message:string;

  receiveMessage($event) {
    this.message = $event
  }
}

child.component.ts

import { Component, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-child',
  template: `
      <button (click)="sendMessage()">Send Message</button>
  `,
  styleUrls: ['./child.component.css']
})
export class ChildComponent {

  message: string = "Hola Mundo!"

  @Output() messageEvent = new EventEmitter<string>();

  constructor() { }

  sendMessage() {
    this.messageEvent.emit(this.message)
  }
}

请访问https://angularfirebase.com/lessons/sharing-data-between-angular-components-four-methods/了解其他方法。

使用输入和输出装饰器

基本概念---> 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;
  }

组件1.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)
  }

组件2.ts:

 @Input() elm: any;

  constructor() { }

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

解决方案 1 使用通用的可注入服务

共享服务.ts

@Injectible()
class SharedService {
function getData():any{
       return this.http.get('/name',{responseType:"json"}).subscribe(
           response => {
                console.log("data :"+response);
                console.log("data stringify:"+JSON.stringify(response));

           });   

     }      

}

解决方案 2 使用父子组件

第二个.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-first-component',
  template: `<p>{{data}}</p>`
})
export class SecondComponent{
data:any={};
ngOnInit(){this.getData();}

function getData():any{
 this.http.get('/name',{responseType:"json"}).subscribe(
   response => {
        console.log("data :"+response);
        console.log("data stringify:"+JSON.stringify(response));
        this.data=data
   }); 
 } 
}

父组件.ts

import { Component }                from '@angular/core';
import { SecondComponent }  from './second.component';

@Component({
  selector: 'app-first-component',
  template: `
  <h3>Get data (via local variable)</h3>
  <button (click)="second.getData()">GetData</button>
  <app-first-component #second></app-first-component>
  `
})
export class FirstComponent{ }

您可以为您的“全球”数据创建存储服务:

store.service.ts

import { Injectable } from '@angular/core';

@Injectable()
export class StoreService {
  protected store: Map<string, any> = new Map();

  constructor() { }


  public get(key: string): any {
    return this.store.get(key);
  }

  public set(key: string, value: any) {
    this.store.set(key, value);
  }

}

然后在你的组件中(让我们称之为 X)你保存数据来存储:

x.component.ts

import { Component, OnInit } from '@angular/core';
import { HttpClinet } from '@angular/common/http';
import { StoreService } from './store-service.service.ts';

@Component({
  selector: 'app-x',
  templateUrl: './x.component.html',
  styleUrls: ['./x.component.css']
})
export class XComponent implements OnInit {

  constructor(
    private store: StoreService,
    private http: HttpClient,
  ) { }

  ngOnInit() {
  }

  getResource() {
      this.http.get('/name',{responseType:"json"}).subscribe(
        response => {
        this.store.set('response', response);
        console.log("data :"+response);
        console.log("data stringify:"+JSON.stringify(response));

   }); 

}

然后在你的其他组件中(我们称之为 Y)你得到你的数据:

y.component.ts

import { Component, OnInit } from '@angular/core';
import { StoreService } from './store-service.service.ts';

@Component({
  selector: 'app-y',
  templateUrl: './y.component.html',
  styleUrls: ['./y.component.css']
})
export class YComponent implements OnInit {

  constructor(
    private store: StoreService
  ) { }

  ngOnInit() {
  }

  getSavedResponse() {
     // ask store for the resource
     return this.store.get('response');
   }); 

}

这只是一个简单的示例,如果您知道通过 http 调用获得的响应结构,那么制作它的模型是个好主意。 使用 store 任何组件都可以获取或设置 store 数据。

如果您需要更复杂的东西,请查找: @ngrx/store

不需要门店服务的情况:

  • 如果您在父组件中执行该 http 调用,那么您可以使用子输入来传递数据。

  • 如果您在子组件中进行该调用,则使用@Output 和 EventEmitter 来传递数据(只是一个级别,您不能这样做以传递给祖父母)

问候。

暂无
暂无

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

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