[英]How to share data between angular components which are not directly linked with each other?
我正在構建一個角度應用程序。 我正在通過單擊事件從第一個組件導航到第二個組件。 在導航到第二個組件時,我希望將一些數據從第一個組件傳遞到第二個組件。 我已經按照教程來實現這一點,但無法做到。 下面是我的代碼
第一個組件.ts
export class FirstComponent implements OnInit {
@Output() messageEvent = new EventEmitter<string>();
constructor(){
}
ngOnInit() {}
sendMessagetoSecond(ahu) {
this.messageEvent.emit(ahu)
console.log(ahu)
}
第一個組件.html
<map name="ahuMap">
<area shape="rect" coords="818,232,917,262" (click)="sendMessagetoSecond()" [routerLink]="['/secondComponent']">
</map>
第二個組件.ts
ahu : string
receiveMessage($event) {
this.ahu = $event
}
第二個組件.html
<body>
<app-first (messageEvent)="receiveMessage($event)"></app-first>
ahu: {{ahu}}
<div>
....
</div>
</body>
這是我嘗試過的。 我面臨的問題是:
1-變量沒有被轉移到第二個組件
第一個組件的 2-HTML 也在第二個組件中加載。
我有什么遺漏或做錯了嗎?
您可以使用共享服務在組件之間傳遞數據。 當你有隨時間變化的數據時,RxJS BehaviorSubject 在這種情況下將非常有用。它將確保組件始終接收最新的數據。
為此,
您首先需要創建一個服務,您將在其中添加一個私有 BehaviorSubject,該服務將保存要在組件之間共享的消息的當前值。 以及兩種方法,一種將當前數據流作為可觀察對象處理,供組件使用,另一種用於更新消息的值。
數據服務.ts
import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
@Injectable()
export class DataService {
private messageSource = new BehaviorSubject('default message');
constructor() {}
fetchMessage(): Observable<string> {
return this.messageSource.asObservable();
}
sendMessage(message: string) {
this.messageSource.next(message)
}
}
創建服務后,您只需將其注入組件的構造函數中,然后調用其方法 fetchMessage/sendMessage 即可獲取或更改您的消息值。
因此,您可以通過以下方式將數據從父級傳遞給子級,例如:
父組件.ts
import { Component, OnInit } from '@angular/core';
import { DataService } from "./data.service";
@Component({
selector: 'parent',
template: `
{{message}}
<button (click)="newMessage()">send Message</button>
`
})
export class ParentComponent implements OnInit {
message:string;
constructor(private data: DataService) { }
ngOnInit() {
this.data.fetchMessage.subscribe(message => this.message = message)
}
newMessage() {
this.data.sendMessage("Hello from Parent Component")
}
}
子組件.ts
import { Component, OnInit } from '@angular/core';
import { DataService } from "./data.service";
@Component({
selector: 'child',
template: `
{{message}}
`
})
export class ChildComponent implements OnInit {
message:string;
constructor(private data: DataService) { }
ngOnInit() {
this.data.fetchMessage().subscribe(message => this.message = message)
}
}
希望這可以幫助你。
在這個演示中,我從 app.component.ts 傳遞一個值來使用 test.service 查看 component.component.ts
在這里,在 app.component.ts 的構造函數中,給 test.service 中的變量賦值,然后將該值賦給一個變量到 view component.component.ts 中。
做到這一點的方法是使用 observables。 您可以根據需要使用主題或行為主題。 然后你可以從另一個組件訂閱並采取相應的行動。 所以實現如下:
@Injectable({ providedIn: 'root' })
導出類 MessageService { 私有主題 = 新主題();
sendMessage(message: string) {
this.subject.next({ text: message });
}
clearMessages() {
this.subject.next();
}
getMessage(): Observable<any> {
return this.subject.asObservable();
}
}
因此,在另一個組件中,您可以像下面這樣訂閱:
constructor(private messageService: MessageService) {
// subscribe to home component messages
this.subscription = this.messageService.getMessage().subscribe(message => {
if (message) {
this.messages.push(message);
} else {
// clear messages when empty message received
this.messages = [];
}
});
}
對於發射部分,我們可以在下面做:
export class HomeComponent {
constructor(private messageService: MessageService) { }
sendMessage(): void {
// send message to subscribers via observable subject
this.messageService.sendMessage('Message from Home Component to App Component!');
}
clearMessages(): void {
// clear messages
this.messageService.clearMessages();
}
}
這些只是選擇的示例代碼,您可以根據需要添加多個訂閱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.