0

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);
  }

}
3
  • Can you indicate how the app was broken when dataService was added (what error message and/or behavior) ? How are you using this dataService in the BodyComponent ? Commented Dec 23, 2020 at 20:00
  • so basically nothing would load on the screen, and if I inspect the page, the <app-header> and <app-body> sections appear, but there is nothing inside of them. I am also missing my <app-footer> Commented Dec 23, 2020 at 20:54
  • the use of the dataService will be to add movies to a list, or remove from the list. Commented Dec 23, 2020 at 21:03

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

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

That should fix your errors.

1 Comment

this solved the issue with things not loading, thank you!
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.