Angular 将数组传递给另一个(非子)组件

Angular pass array to another (NOT child) component

我是 Angular 的新手,在将数组传递给其他(与 parent/child 无关)的组件时遇到问题。我在我的应用程序中想要的是点击一个按钮将其标记为'accepted',并在不同的视图(接受的数组视图)中显示相同的数组,在一条不同的路线。我已经 尝试使用 @Input 和共享服务 来完成它,但它就是行不通。你能给我指出正确的方向吗?谢谢。

sharedService.ts //My array is called 'Turno'

    import {Injectable} from '@angular/core';
    import {Turno} from '../models/turno';


    @Injectable()

    export class SharedService{


    public turno:Turno;


        constructor(){

        }



setArray(turno){
    this.turno=turno;
}
getArray(){

    return this.turno;
}
}

第一个组件(我用 accept() 方法标记了一个接受的数组):

@Component({
  selector: 'app-turnos',
  templateUrl: './turnos.component.html',
  styleUrls: ['./turnos.component.css'],
  providers:[TurnoService, SharedService]
})
export class TurnosComponent implements OnInit {

    public turnos: Turno;
    public status;


  constructor(

    private _turnoService: TurnoService,
    private _sharedService: SharedService

    ) { }

  ngOnInit(): void {

    this._turnoService.getTurnos().subscribe(
        response=>{
            if(response.status== 'success'){
                this.turnos= response.turnos;
                this.status=response.status;
                console.log(this.turnos);
            }else{
                this.status= 'error';
            }

        },error=>{
            console.log('error');
        }

        );

  }

  accept(turno){

    this._sharedService.setArray(turno);
    console.log(turno);


  }

第二个组件(接收并列出接受的数组)

import { Component, OnInit} from '@angular/core';
import {SharedService} from '../../services/shared.service';
import {Turno} from '../../models/turno';

@Component({
  selector: 'app-turnoaceptado',
  templateUrl: './turnoaceptado.component.html',
  styleUrls: ['./turnoaceptado.component.css'],
  providers:[SharedService]
})
export class AcceptedTurnoComponent implements OnInit {

        public turnos: Turno;


  constructor(
    private _sharedService: SharedService

    ) { }


  ngOnInit(): void {
    this.turnos=this._sharedService.getArray();
    console.log(this.turnos);
  }



}

Angular中主要有3种数据通信方式。

    1. Using Input & Output for passing data to & from child component. 
       Also you can use ViewChild reference to access data (functions & 
       variables) of child component in parent component.
    2. A shared common service having setter & getter methods. 
       You can use it to set data. It acts as a temporary state.
    3. Using Browser storage in the form of session storage , local storage 
       or cookie. You can create one service which stores & takes in data 
       from browser storage & access it across components.

在这种情况下,共享服务是必经之路。

每次添加新项目时发出数组的服务:

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

@Injectable({
  providedIn: 'root',
})
export class ArrayServiceService {
  private acceptedArray = [];
  public acceptedArraySubject = BehaviorSubject<string[]>([]);

  addToAccepted(item: string) {
    this.acceptedArray.push(item);
    this.acceptedArraySubject.next(this.acceptedArray);
  }

  constructor() {}
}

调用服务添加项目的服务 (当然,你从哪里得到你的物品取决于你,我相信你知道如何通过点击事件传递物品,所以我没有显示 html):

import { Component, OnInit } from '@angular/core';
import { ArrayService } from '../array.service';

@Component({
  selector: 'app-first-component',
  templateUrl: './first-component.component.html',
  styleUrls: ['./first-component.component.scss'],
})
export class FirstComponentComponent implements OnInit {

  private allItemsArray = ['item1', 'item2', 'item3'];

  markAsAccepted(item: string) {
    this.arrayService.addToAccepted(item);
  }

  constructor(private arrayService: ArrayService) {}

  ngOnInit(): void {}
}

最后,第二个组件侦听服务内部的变化并显示接受的数组:

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { ArrayService } from '../array.service';
import { share } from 'rxjs/operators';

@Component({
  selector: 'app-second-component',
  templateUrl: './second-component.component.html',
  styleUrls: ['./second-component.component.scss'],
})
export class SecondComponentComponent implements OnInit {
  private acceptedArray: Observable<string[]>;

  constructor(private arrayService: ArrayService) {
    this.arrayService.acceptedArraySubject.pipe(share());
  }

  ngOnInit(): void {}
}

并使用第二个组件的 html 中的管道:

<ul>
  <li *ngFor="let item of acceptedArray | async">{{item}}</li>
</ul>

希望这能让您走上正轨。所以你有一个服务来保存你想要的数组,一个改变它的组件和另一个监听它的组件。但是你可以让很多组件监听它或改变它..