簡體   English   中英

如何將帶有 id 的數組從一個組件傳遞到另一個組件(角度)

[英]How to pass an array with id's from one component to another (angular)

你好朋友這是我在這里的第一個問題。

我在一個角度項目中遇到這種情況,我需要將 id 數組從一個組件傳遞到另一個非常不同的組件,兩者之間沒有關系我這么說是因為我發現的所有問題都說要使用 viewchild、輸入、輸出但我認為我不能這樣做,因為當我單擊從數組中的第一個組件獲取 id 的按鈕時,應該使用角度路由器導航到另一個組件,所以有辦法做到這一點嗎?

順便說一句:一位朋友告訴我使用 url 參數,但我必須是“x”個 id,所以我不知道它是否正確答案

對不起我的英語我希望清楚

只需創建一個服務,將您的數據保存在一個變量中,並在需要時將其返回給您,如下所示

服務代碼:

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

@Injectable('root')
export class DataService {
  private dataArr = [];

  constructor(){}  

  setArrData(val){
    this.dataArr = [...val]; //creates a new reference 
  }

  getArrData(){
   return this.dataArr;
  }
}

具有數組數據的組件,並確保您將數據設置為服務並開始您的路線

import { Component } from '@angular/core';
import { DataService } from 'path to service file';

@Component({
  selector: 'component-that-has-array',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class ComponentOne  {
  name = 'Angular 6';
  constructor(private dataService :DataService){

  }

  data=["1","2"];
  dataService.setArrData(data);
}

路由后必須接收數據的組件

import { Component,OnInit } from '@angular/core';
import { DataService } from 'path to service file';

@Component({
  selector: 'component-that-recieves-array',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class ComponentTwo implements OnInit  {
  constructor(private dataService :DataService){  }
  ngOnInit(){
   data=dataService.getArrData();
  }

}

您可以使用 rxjs 中的 BehaviorSubject 以便在組件之間共享數據

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

@Injectable()
export class DataService {

  private dataSource = new BehaviorSubject<any>({});
  data = this.dataSource.asObservable();

  constructor() { }

  updatedDataSelection(data: any){
    this.dataSource.next(data);
  }

}

在你的組件文件中:

//inject service into a component

...

dataService.data.subscribe(data => {
  //do what ever needs doing when data changes
})

...

//update the value of data in the service
dataService.updateData(newData);

暫無
暫無

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

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