簡體   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