Home > Back-end >  How do I send data into an Angular component only once (since @Input listens for updates all the tim
How do I send data into an Angular component only once (since @Input listens for updates all the tim

Time:12-02

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() )

CodePudding user response:

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)

CodePudding user response:

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.

  • Related