簡體   English   中英

如何在 Angular 2+ 中沒有“父子”關系的情況下動態地將數據從一個組件傳遞到另一個組件?

[英]How to pass data from one component to another dynamically without "Parent-Child" relationship in Angular 2+?

這是一個開放的討論,但我真的很好奇將數據從一個組件動態傳遞到另一個組件。

我知道可以使用@Input()裝飾器來完成。 但它也有缺點,比如您不能使用瀏覽器上的后退按鈕。 因為如果你這樣做,那么你將返回整個頁面。 它不會在Parent-Child方法中工作,因為我們使用ng-If來隱藏頁面上的子指令,並且除非您重新加載該頁面,否則它不會動態更新內容。 當您重新加載該頁面時,您將丟失 UI 的當前 state。

如果數據是 static 那么絕對沒有問題,但是當它是動態的並且您嘗試傳遞數據時,它顯示為undefined

我將不勝感激有關如何實現這一目標的任何指示。

另一種方法是使用服務 您必須將該服務用作數據值的“存儲”:

  1. 創建服務:
ng g s MyServiceName --skip-Tests

創建后,檢查是否已裝飾為 providedIn root:

@Injectable({
  providedIn: 'root',
})
export class MyServiceNameService {
....
  1. 在您的服務中,聲明您希望組件共享(共有)的所有數據,並為這些數據創建方法 setters/getters。 例如:
private _myVariable: string;

get myVariable(){
   return _myVariable;
}

set myVariable(newValue: string){
   this._myVariable = newValue;
}

constructor(){
   _myVariable = "exampletest";
}



  1. 在組件的構造函數中注入服務(在父組件和子組件中):
...
import { MyServiceNameService } from '../../services/my-service-name.service';
...
constructor(
   private myServiceNameService : MyServiceNameService ) {
  }
...
  1. 通過服務中的方法直接使用服務中的變量來修改變量值或獲取其值。

例如:在組件中:

let myVariable:string;

....
getNewValue(){
   myVariable = this.myServiceNameService.myVariable;
}
setNewValue ( newValue: string) {
   this.myServiceNameService.myVariable(newValue);
}

這里可能有多種方式:

  1. 您可以創建 angular 服務(使用 @Injectable() 注釋創建服務)。 Angular 服務遵循 singleton 設計模式,可以在您的應用程序的多個頁面之間共享。 無論您在哪里需要,只需注入該服務,您就可以訪問所有屬性/方法。
    鏈接如何創建angular服務-

    https://angular.io/guide/architecture-services

  2. 您可以使用 redux 概念並創建一個包含數據的商店,然后可以跨所有頁面訪問該數據。 NgRx 是最好的庫 Angular 可以在任何需要的地方創建存儲和訪問數據。 NgRx 鏈接 -

    https://ngrx.io/guide/store

  3. 您可以使用 RxJs 庫在對等組件之間共享數據。
    RxJs 鏈接 -

    https://rxjs.dev/guide/overview

使用共享服務並在服務內部創建一個可觀察對象,然后將此服務注入需要訪問此共享數據的組件並在每個組件上創建訂閱。 當 observable 中的數據發生變化時,訂閱的組件將得到通知。

您可以使用 Service 本身來做到這一點:

  1. 創建服務

    在服務中創建一個主題...

@Injectable({
 providedIn: 'root'
})

export class Service {

   subject = new Subject();
   
   
    sendMsg(msg: string) {
       this.subject.next(msg);
     }
   
     receivedMsg(): Observable <any> {
       return this.subject.asObservable();
     }
}
  1. 我們從中發送數據的 Component-1。

    在構造函數中注入服務。 那么您需要將數據作為參數傳遞給sendMsg方法。

    component-1.ts 中

    constructor(private Ser: Service) {}

    sendMsg(msg: any) { 
       this.Ser.sendMsg(msg.value); 
    } 
  1. Component-2 用於接收數據。

    在構造函數中注入服務。

    search: string;

    constructor(private Ser: Service) {}
    
    ngOnInit(): void { 
       
    this.Ser.receivedMsg().subscribe({
      next: (data: any)=> {
        this.search= data;
      }
    })
   }

您將在搜索變量中獲取數據。

暫無
暫無

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

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