When I click on a button I should get the data, but I have to press it twice.
Here I call getPeople () to get an array with the data and then I call getPerson () in the service connection-person-service;
export class DetailUserComponent implements OnInit {
detailPerson: Person;
@Input() id;
constructor(
private route: ActivatedRoute,
private conexion: ConexionPersonService) { }
ngOnInit() {
this.id = +this.route.snapshot.paramMap.get('id');
this.conexion.getPeople();
this.getPerson();
}
getPerson(): void {
this.detailPerson = this.conexion.getPerson(this.id);
console.log('al final obtengo' , this.detailPerson );
}
}
In the service connection-person-service: I get the Array with the people, I also have the console log "ANTESOBTENIDO" that will give undefined the first time
@Injectable()
export class ConexionPersonService {
_people: Person[];
constructor(
private http: HttpClient,
) { }
public getPeople() {
const url = 'assets/Json/listPerson.json';
this.http.get<Person[]>(url).subscribe(data => {this._people = data});
console.log('ANTESobtenido ' , this._people);//aqui
}
public getPerson(id:number): Person{
console.log('ID ' , id);
if(this._people) {
var per = this._people.find(person => person.id_user == id);
console.log('obtenido ' , per);
return this._people.find(person => person.id_user == id);
}
}
}
As you can see in the img the first time I give it does not work, the next time I click on it, it already shows me the data.