簡體   English   中英

如何顯示從一個組件發送到另一個組件的結果?

[英]How to show results sending from one component to other component?

我有一個過濾器組件:ExtendedSearch 組件。 我有一個列表組件,它必須從擴展搜索組件中獲取結果。 我有一個由 ExtendedSearch 調用使用的服務調用。

嘗試參考我給出的類似問題的這個答案( Angular 8: pass a data to a router )。 它有 4 種方法來處理這個問題。

  1. 父母對孩子:通過Input()共享數據
  2. Child to Parent:通過ViewChild共享數據
  3. Child to Parent:通過Output()EventEmitter共享數據
  4. 不相關的組件:與服務共享數據(推薦)

希望這會有所幫助!

祝你好運!

您可以使用@Input@Output事件發射器通過不同的組件共享結果。 閱讀更多

通過服務,您可以這樣做

Service.ts
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable()
export class DataService {

  private messageSource = new BehaviorSubject('default message');
  currentMessage = this.messageSource.asObservable();

  constructor() { }

  changeMessage(message: string) {
    this.messageSource.next(message)
  }

}


Parent.ts 
import { Component, OnInit } from '@angular/core';
import { DataService } from "../data.service";

@Component({
  selector: 'app-parent',
  template: `
    {{message}}
  `,
  styleUrls: ['./sibling.component.css']
})
export class ParentComponent implements OnInit {

  message:string;

  constructor(private data: DataService) { }

  ngOnInit() {
    this.data.currentMessage.subscribe(message => this.message = message)
  }

}
sibling.ts
import { Component, OnInit } from '@angular/core';
import { DataService } from "../data.service";

@Component({
  selector: 'app-sibling',
  template: `
    {{message}}
    <button (click)="newMessage()">New Message</button>
  `,
  styleUrls: ['./sibling.component.css']
})
export class SiblingComponent implements OnInit {

  message:string;

  constructor(private data: DataService) { }

  ngOnInit() {
    this.data.currentMessage.subscribe(message => this.message = message)
  }

  newMessage() {
    this.data.changeMessage("Hello from Sibling")
  }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM