Reputation: 57
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);
}
}
Upvotes: 0
Views: 433
Reputation: 22343
It looks like you forgot to add where your service is provided:
@Injectable({
providedIn: 'root',
})
That should fix your errors.
Upvotes: 1
Reputation: 1870
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.
Upvotes: 0
Reputation: 800
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.
Upvotes: 1