Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

72
Views
How do I send data into an Angular component only once (since @Input listens for updates all the time)

I have an Angular Scroller component

<app-scroller></app-scroller> 

that provides a skeleton for displaying an array of images

Random Component

<app-scroller [init]="getImages('cats')"></app-scroller>
<app-scroller [init]="getImages('dogs')"></app-scroller>
getImages(src: string) {
  //THIS FUNCTION GETS CALLED AGAIN AND AGAIN
  return {
    aspect: '16/9',
    res: 'min',
    sources: this.imageService.getImagesFromAPI(src)
  };
}

Scroller Component

public movies: string[] = [];
@Input() init: {aspect: string, res: string, sources: Promise<string[]>};

ngOnInit() {
  this.init.sources.then(images => this.movies = movies);
}

but this results in the the getImages and therefore the sources Promise to be executed over and over

Is there a way I can send data to the Scroller component only once (therefore without using @Input() )

7 months ago · Juan Pablo Isaza
3 answers
Answer question

0

Use property binding only to send the category id (dogs/cats) to the component and call getImages(cateogryID) only once in the child component.

Parent component

<app-scroller [categoryId]="catIdProperty"></app-scroller>

Child component:

@input()
categoryId: string;

images: [type here] = [initialization here];


ngOnInit(): void {

  this.images = this.getImages(categoryId); // Btw, could getImages() reside in the imageService?

}
7 months ago · Juan Pablo Isaza Report

0

I believe you need to call your service once to get the array of images and save it inside your component as a property,

something like this

myService.getData.subscribe(data=> this.catImages = data)
7 months ago · Juan Pablo Isaza Report

0

If I understand your question and setup correctly, you are asking about preventing an @Input from listening, what if you instead prevent data from emitting to this input?

You could deliver an observable stream that emits just once, eg.

catImages$ = this.catDataFromService$.pipe(
  take(1),
)

<app-scroller [source]="catImages$ | async"></app-scroller>

Alternatively, you could construct your own Observable and complete it when necessary.

7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs