簡體   English   中英

如何在 Angular 8 中的組件之間共享數據

[英]How to share data between components in Angular 8

我正在嘗試使用服務將數據從一個組件共享到另一個組件,例如正文組件到標題組件,但不工作。 單擊更改標題詳細信息按鈕后,我想更改標題數據詳細信息,例如 ID 和名稱。

body.component.ts:

  change(){ 
  this.details = {
    id:"45673",
    name:"Micheal"
  } 
  this.data.changeMessage(this.details);  
  }

common.service.ts:

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
@Injectable()
export class CommonService {

 details={
   id:'12345',
   name:'Victor'
 }

  private messageSource = new BehaviorSubject(this.details);
  currentMessage = this.messageSource.asObservable();

  constructor() { }

  changeMessage(message: any) {
    this.messageSource.next(message);
  }

}

演示: https : //stackblitz.com/edit/angular-ep7tes?file=src%2Fapp%2Fbody%2Fbody.component.ts

嘗試這個:

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

HTML:

<p>
body component:
</p>

<div *ngIf="message">


 {{message.id}}
 {{message.name}}
 </div>

https://stackblitz.com/edit/angular-xhqbti?file=src%2Fapp%2Fcommon.service.ts

您更改兩行代碼並重試

 {{names.id}} <====={{details.id}}

   {{names.name}}<====={{details.name}}

我認為這對你有用

如果您的數據經常變化並且每次都需要最新數據,您可以使用 Behavior 主題在組件之間共享數據。

否則,您可以簡單地使用服務在組件之間共享數據。

  1. https://www.c-sharpcorner.com/article/angular-services-for-sharing-data-between-component-using-angular-and-above/

  2. https://medium.com/@luukgruijs/understanding-rxjs-behaviorsubject-replaysubject-and-asyncsubject-8cc061f1cfc0

暫無
暫無

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

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