Home > Software design >  How to initialice a variable with the first instance of an array that comes from a server
How to initialice a variable with the first instance of an array that comes from a server

Time:06-16

image of the problem and the seeked result

Here you can see the first component, which gets data from the server, that I couldn't set the selected panel to be activated. The second component, which still gets the data from a mock list, is the visual result i'm after (i.e. having the array[0] to be assingned to the selectedSomething variable).

I have a service for retrieving the data from a mock server and a component that displays it.

Service code:

export class ExperienceService {
  private experiencesUrl = 'http://localhost:5000/experiences';

  constructor(private http: HttpClient) {}

  getExperiences(): Observable<Experience[]> {
    return this.http.get<Experience[]>(this.experiencesUrl);
  }
}

Component code:

export class ExperienceComponent implements OnInit {
  experiences: Experience[] = [];
  selectedExperience: Experience = this.experiences[0];

  constructor(private experienceService: ExperienceService) {}

  ngOnInit(): void {
    this.getExperiences();
  }

  getExperiences() {
    this.experienceService
      .getExperiences()
      .subscribe((experiences) => (this.experiences = experiences));
  }

  onSelect(experience: Experience): void {
    this.selectedExperience = experience;
  }
}

So, how do I make the component variable "selectedExperience" to be initialiced with experiences[0]?

(to be clear, the rest of the code is working, when I click the buttons on the left the onSelect function works and each panel appears, but I want the one on the top to be selected from the start)

CodePudding user response:

How about initialising it in the subscribe() callback?

this.experienceService
  .getExperiences()
  .subscribe((experiences) => {
    this.experiences = experiences
    this.selectedExperience = experiences[0]
  });
  • Related