如何将订阅函数传递给父组件?(角度)

时间:2019-04-21 12:47:18

标签: angular rest

如何传递订阅功能,从REST API中将信息从子组件(agreements.component)传递到父组件(home.component),并在子组件中使用ngOnInit()中的事件发射器调用它。我将不胜感激任何帮助。 我附上了代码。

儿童组件协议。

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

@Component({
  selector: 'app-agreements',
  templateUrl: './agreements.component.html',
  styleUrls: ['./agreements.component.sass']
})
export class AgreementsComponent implements OnInit {
  @Output() getBody = new EventEmitter<any>();
  private body;
  constructor() { }

  ngOnInit() {
    this.body=this.getBody.emit();
  }

}
<ul>
  <li *ngFor="let b of body">{{b.body}}</li>
</ul>

服务

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class AgreementsService {

  constructor(private http:HttpClient) { }

 // Uses http.get() to load data from a single API endpoint
 getBodyService(): Observable<any> {
  return this.http.get('https://jsonplaceholder.typicode.com/posts');
  }
}

父组件(home.component)

import { Component, OnInit } from '@angular/core';
//import {Customer} from '../model/model';
import {AgreementsService} from '../home/agreements/agreements.service';


@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.sass']
})
export class HomeComponent implements OnInit {
  private body;
  constructor(private _agreementsService: AgreementsService) { }

  ngOnInit() {
  }

  getBody() {
    return this._agreementsService.getBodyService().subscribe(
        data => { this.body = data, console.log(data)},
        err => console.error(err),
        () => console.log('done loading foods')
      )
    }

}
<app-email></app-email>
<app-agreements (getBody)="getBody($event)"></app-agreements>

2 个答案:

答案 0 :(得分:1)

不,你不能那样做,但是有2个选择

  • ViewChild

通过@ViewChild在home组件中获取应用协议组件,当数据到来时,您将像这样调用应用协议功能

@Component({
  selector: "app-home",
  templateUrl: "./home.component.html",
  styleUrls: ["./home.component.sass"]
})
export class HomeComponent implements OnInit {
  private body;

  @ViewChild(AgreementsComponent)
  agreementsComp: AgreementsComponent;

  constructor(private _agreementsService: AgreementsService) {}

  ngOnInit() {}

  getBody() {
    return this._agreementsService.getBodyService().subscribe(
      data => {
        this.agreementsComp.processData(data);
      },
      err => console.error(err),
      () => console.log("done loading foods")
    );
  }
}

并在内部协议组件中添加processData方法。

第二个更好的选择

  • 属性绑定

将输入属性添加到协议组件中,并在数据到来时对其进行分配,并像这样在协议组件中监听ngOnChanges事件

export class AgreementsComponent implements OnInit, OnChanges {

  @Output() getBody = new EventEmitter<any>();

  @Input() data: any;

  private body;

  constructor() {}

  ngOnInit() {}

  ngOnChanges() {
    if (data) {
      ///Do your logic here
    }
  }
}

这是html的首页组件

<app-agreements [data]="body" (getBody)="getBody($event)"></app-agreements>

答案 1 :(得分:1)

无需使用 EventEmitter 。将正文作为 Input 传递给子组件。

ParentComponent-HTML

<div *ngIf="body">
 <app-agreements [body]="body"></app-agreements>
</div>

ParentComponent-TS

  ngOnInit() {
    this.getBody();
  }

  getBody() {
    this._agreementsService.getBodyService().subscribe(
        data => { 
        this.body = data;
        },
        err => console.error(err),
        () => console.log('done loading foods')
      )
  }

ChildComponent-TS

export class AgreementsComponent {

     @Input() body;

}

见我的StackBlitz Demo