簡體   English   中英

使用在 Angular 中返回空的共享服務在兄弟組件之間共享數據

[英]Sharing Data between Sibling Components using Shared Service returning empty in Angular

我試圖在 Angular 中的兩個兄弟組件之間共享一個字符串,但它似乎對我不起作用。

我有兩個組件, auth.component.tsupdate.component.ts 然后我有一個名為shared.service.ts的服務。

編輯 2:我按照評論中的建議包含了整個shared.services.ts文件。

共享服務.ts

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

@Injectable({
  providedIn: 'root'
})

export class SharedService {

  private useridSource = new BehaviorSubject('empty');

  useridMessage$ = this.useridSource.asObservable();

  constructor() { }

  sendUserId(userId:string) {
    this.useridSource.next(userId);
  }
}

auth組件的目的是允許用戶通過 firebase 的身份驗證方法登錄/注冊。 然后我檢索用戶的唯一 ID 並希望將該字符串傳遞給update.ts組件,以便它可以在 Firebase 實時數據庫中以該名稱創建一個節點。 請注意,我在使用firebase時也使用了Angular Fire 庫

以下是來自auth.component.ts的代碼片段

  //I store the unique ID created by firebase in this string
  userId?:string;

  //I inject the AngularFireAuth from the Angular Fire library as well as my Shared Service 
  constructor(public auth: AngularFireAuth, private sharedService: SharedService ) { }

  //the user logs in or signs up using google
  login() {
    this.auth.signInWithPopup(new firebase.auth.GoogleAuthProvider());
  }

  //this function sets the userId string - if I console.log() this string, it prints out correctly
  printUserId() {
    this.auth.authState.subscribe( authState => {
      this.currentAuth = authState;
      this.userId = this.currentAuth.uid;
    })
  }

  //I use this function to send the data via the shared service when a button is pressed in the HTML file. 
  sendUserData(){
    if(this.userId) {
      console.log(this.userId);
      this.sharedService.sendUserId(this.userId);
    } else {
      console.log("User Id has not been set");
    }
  }

auth.component.html文件中,我通過以下方式將數據發送到服務:

  <button (click)="sendUserData()"> Send Current User </button>

update.component.ts 中,我收到了數據並想打印出來。

  //string to receive the data in 
  userId?:string;

  //inject the shared service. The CrowboxdbService is another service I use to interact with firebase
  constructor(private cbservice: CrowboxdbService, private sharesService: SharedService) {
  }

  //this function is invoked when a button is pressed in the view (HTML file)
  getUserId(){
    this.sharesService.useridMessage$.subscribe(x => {
      this.userId = x;
      console.log(this.userId);
    }  
    );
  }

update.component.html


<button (click)="getUserId()">Get User ID </button>
<h1>User Id is: {{userId}}</h1>

因此,當我嘗試通過auth.component.ts文件中的sendUserData sendUserData()發送數據時,它起作用了。 我也可以在控制台窗口中打印用戶 ID。 然而,在update.component.ts中,當我訂閱 observable 時,我仍然收到“空”。 這是否意味着它沒有改變價值?

我已經嘗試在兩個ts文件中訂閱ngOnInit()中的可觀察對象,但仍然沒有返回正確的值。 我錯過了什么嗎? 我一直在關注本教程

編輯 1:重要說明(我認為?),這兩個組件也用作兩條不同的路線。 這是app-routing.module.ts 中設置的路由

const routes: Routes = [
  { path:'', component:TestUpdateComponent },
  { path:'auth', component:AuthComponentComponent }
];

好吧,我檢查了您的代碼,問題可能由很多原因引起,但我認為問題在於您在多個模塊中提供了此服務。

確保您只在聲明了兩個組件的模塊或app.module.ts提供此服務

我的建議是創建一個components.module.ts並在那里聲明您的所有組件,以便您可以將它導入到您想要的任何位置。

我還建議您在服務中聲明一個公共變量,而不是這種混淆的 setter 和 getter,這樣您就可以在任何地方更新它,並且它會在其他地方更新。

問題實際上與我試圖在不同路由中的組件之間共享數據的事實有關。 因此,這些是不相關的組件,我無法使用共享數據的標准方法(例如,從父組件到子組件或在兄弟組件之間)。

我遵循了這個網站的第三個例子。 我通過ng gs shared命令創建了一個簡單的服務。 我將此服務導入到我的app.module.ts文件中,並將其作為providers之一包含在內。

shared.service.ts文件非常簡單,因為我只想傳遞一個字符串:

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

@Injectable({
  providedIn: 'root'
})

export class SharedService {

  public userId:any;

  constructor() { }
}

然后,在需要發送數據的文件auth.component.ts 中,我有一個通過單擊按鈕執行的函數。 此函數檢查所討論的字符串是否先前已設置(在這種情況下由用戶登錄)。 如果設置了字符串,則在提供程序文件中設置字符串並導航到接收器組件頁面。

  //function is invoked by a button in the view page 
  sendUserData(){
    if (this.userId) {
      this.sharedService.userId = this.userId;
      this.router.navigate(['data']);
    } else {
      console.log("User Id has not been set");
    }
  }

為了在update.component.ts 中接收數據,我有一個簡單的函數,它也可以通過單擊按鈕來執行:


  getUserId(){
    this.userId = this.sharesService.userId;
    console.log(this.userId);    
  }

這將打印出值。 如果我沒記錯的話,這個方法還使所有可以訪問該特定提供程序的組件全局使用該變量。

暫無
暫無

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

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