簡體   English   中英

如何在 Angular 中將數據從一個組件傳遞到另一個組件?

[英]How do I pass data from one component to another in Angular?

我正在使用 Angular 開發一個測驗應用程序。 我需要在我的 ResultsComponent 中獲取正確答案計數的值。 當我在測驗結束時確實需要總正確答案的值時,我在 ResultsComponent 中得到了正確答案計數的值 0,並且在測驗期間也得到了 1166 的值來代替正確答案計數。 我認為代碼看起來是正確的,只是我得到的值是錯誤的。 不知道我做錯了什么。 這是我的代碼:

在我的測驗服務中:

    @Injectable({ providedIn: 'root' })
    export class QuizService {
      correctAnswersCountSubject = new BehaviorSubject<number>(0);

      sendCountToResults(value) {
        this.correctAnswersCountSubject.next(value);
      }
    }

在我的 DI 測驗組件中:

    ngOnInit() {
      this.quizService.correctAnswersCountSubject.subscribe(data => {
        this.count = data + 1;
      });
      this.sendCountToQuizService(this.count); 
    }

    sendCountToQuizService(count) {
      this.quizService.sendCountToResults(count);
    }

在我的 ResultsComponent 中:

    constructor(private quizService: QuizService) {}

    ngOnInit() {
      this.quizService.correctAnswersCountSubject.subscribe(data => {
        this.correctAnswersCount = data;
      });
    }

請你幫忙。 謝謝你。

我會給你一些提示,我的幫助。

  • 您應該在 QuizService 上使用@Injectable({providedIn: 'root' })來保證整個應用程序中此服務的 singleton 實例。
  • 在 DI-Quiz 組件中,在訂閱的回調中調用this.sendCountToQuizService
  • 在 ResultsComponent,在 OnInit 鈎子上初始化訂閱(可能使用 pipe 異步顯示計數值)。

編輯:

我認為您在 DIQuizComponent 上通過訂閱和發送新值到同一個地方的同一個主題以某種方式創建遞歸事件。 由於 correctAnswersCountSubject 是一個 BehaviorSubject,因此您無需使用getValue方法訂閱即可獲取 correctAnswersCountSubject 的值。

這次我在stackblitz上創建了一個演示,希望對您有所幫助。

再次編輯:

我已經調試了您的代碼,並通過一些修改解決了所有問題,它們是:

  • QuizQuestionComponent中,在答案 EventEmitter 上添加裝飾器 @Output()。
  • DependencyInjectionQuizComponent ,在 nextQuestion 方法上, this.answer 設置為 null ,然后調用需要答案值的 checkIfAnsweredCorrectly 方法。
  • DependencyInjectionQuizComponent ,您沒有增加 this.count,我是在 checkIfAnsweredCorrectly 方法上完成的。
  • 最重要的是,我刪除了模塊中的所有提供程序,以保證服務的 singleton 實例。

在這里演示: stackblitz

如果你想在組件之間傳遞數據,你有幾個選擇。 我不會假設您的場景以及這些是否會起作用,因為實際上很多時候當我們是新手時,我們意識到我們需要稍微重新架構我們的組件才能實現我們想要的,所以相反,我將分享您可用的方法。

標准數據綁定

如果您嘗試將數據從父組件傳遞到子組件,則可以在將組件添加到父組件時簡單地綁定數據。

父組件.html

<child-component [myData]="myDataAsIsInParentComponent"></child-component>

child.component.ts

@Input() myData: <YourType>;

向上發射數據

如果您嘗試將數據從子組件傳遞到父組件,則可以將值發送到組件樹(也就是冒泡組件樹)

父組件.html

<child-component (myEmitter)="functionToCallInParent($event)"></child-component>

父組件.ts

functionToCallInParent($event) {
  const myPassedData = $event;
}

child.component.ts

@Output myEmitter: EventEmitter<myType> = new EventEmitter<myType>();

現在,這些已在 Angular 開箱即用的解決方案中得到解決。

State管理即Redux等

我強烈建議您通過 NGRX 探索 state 管理解決方案,例如 redux,如果您想擁有一些真正出色的數據存儲和數據傳遞能力。

NGRX 很棒。 一開始對一些人來說有點嚇人,但好處是瘋狂的? 想象一下,在模塊 x 中需要來自模塊 y 的數據,而這兩個模塊都沒有通過組件連接,那么在這種情況下,您將無法在組件樹中向上和/或向下傳遞數據。 但你可以用 redux。

希望這可以幫助。

簡單的解決方案將使用服務作為存儲正確答案計數的存儲。 請找到以下解決方案:

在您的服務中聲明一個私有變量並在服務中為其編寫 getter 和 setter,如下所示:

private correctAnswerCount:number;

//if you are calling this method for each correct answer
incrementCorrectAnswerCount(){
this.correctAnswerCount++;
}

//if you are calling this method once
setCorrectAnswerCount(value:number){
this.correctAnswerCount = value;
}

//you can fetch this method from any compononent so as the value of correctAnswerCount
getCorrectAnswerCount(){
return this.correctAnswerCount;
}

暫無
暫無

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

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