簡體   English   中英

在同級組件Angular 5之間傳遞對象{}

[英]Passing object { } between sibling components Angular 5

我不確定我在做什么錯...

基本上,我有2個同級組件,第一個組件獲取一些數據,我想與同級組件共享該數據,因此我已經提供了服務

服務

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

@Injectable()
export class DataService {
    // Individual Data Source
    private dataSource = new BehaviorSubject<Object>({});
    // Individual Data Source
    data = this.dataSource.asObservable();
    // Individual Data Source
    updateData(data) {
        this.dataSource.next(data);
    }
}

然后在我的第一個組件中...

this.activatedRoute.params.subscribe(params => {
  this.id = params.id;
  this._dataNotification.getSingledataNotification(this.id)
    .subscribe(result => {
      this.data = result;
      this._dataService.updateData(this.data);
    });
});

然后在我的第二部分。

getData() {
    this._dataService.data.subscribe((result) => {
        this.data = result;
        console.log(this.data);
    });
}

基本上發生了什么事是在我的第一個組件中獲取數據對象並將其傳遞給updateData函數,然后在我的第二個組件中獲取數據,但是當我控制台日志時,我僅獲取了一個空對象?

有什么想法我做錯了嗎?

編輯

我將updateData函數放入onChanges生命周期事件中,現在它可以工作了。

多謝你們

這個創建了一個服務來處理消息事件。

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';

@Injectable()
export class MessageService {
  private subject = new Subject<Message>();

  send(key: string, value: any) {
    this.subject.next({ key, value });
  }

  get(): Observable<Message> {
    return this.subject.asObservable();
  }
}

class Message {
  constructor(
    public key: string,
    public value: any) { }
}

這個偵聽事件,並在事件得到執行時執行。

import { Subscription } from 'rxjs/Subscription';
private subscription: Subscription;

constructor(
  private messageService: MessageService,
) {}

ngOnInit() {
  this.subscription = this.messageService.get().subscribe(message => {
    if (message.key === 'what message you want') {
      this.dosth()
    }
  });
}

當您要將對象從一項服務發送到另一項服務時,請調用消息服務中的send並訂閱所需的服務。

當我不得不實施相同的方案時,我遇到了類似的問題。

解決方案是,您不應在onInit()方法內的接收組件中接收數據。 而是通過onChanges()方法或通過事件(如按鈕click )接收它。 它將返回帶有值的對象。

暫無
暫無

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

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