简体   繁体   中英

Pass Array Between Child Components Angular/TypeScript

I am trying to pass an array from one child component to another. I have tried following some of the tutorials online to share data with a service, but this doesn't seem to be working for me and causes my page not to load anything.

What was breaking my program was adding the DataService to the constructor:

import { DataService } from '../data.service';

export class BodyComponent implements OnInit{
  films = [{Title: "Finding Nemo", Rating: "3.5"}, {Title: "Rambo", Rating: "4.0"}];
  constructor(private http: HttpClient, private data: DataService) { }
}

data.service.ts

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

@Injectable()
export class DataService {

  private finalNoms = new BehaviorSubject<any>([]);
  currentNoms = this.finalNoms.asObservable();

  constructor() { }

  changeNominations(nom: Object){
    this.finalNoms.next(nom);
  }

}

In angular it's the service who manages the data. You should put films = [{Title: "Finding Nemo", Rating: "3.5"}, {Title: "Rambo", Rating: "4.0"}]; in your service and access to it in your component by doing in the constructor or ngOnInit:

this.films = this.data.films;

Other thing: you should name (in your component) your service dataService instead of justdata.

It looks like you forgot to add where your service is provided:

@Injectable({
  providedIn: 'root',
}) 

That should fix your errors.

if you are trying to pass an array of data between 2 child components, it's probably best to create 2 ViewChilds in your parent and pass the data up to the parent via EventEmitter and back down to the other child.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM