我在Angular中获取数组时遇到问题 . 它只有在我单击按钮两次才能获得数组时才有效 . 我需要一次点击获取数据(参见页面末尾的Img) .
@Injectable()
export class ConexionPersonService {
_people: Person[];
constructor(
private http: HttpClient,
) { }
public getPeople(): void {
const url = 'assets/Json/listPerson.json';
this.http.get<Person[]>(url).subscribe(data => {this._people = data});
console.log('ANTESobtenido ' , this._people);
}
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);
}
}
}
export class DetailUserComponent implements OnInit {
detailPerson: Person;
People:Person[];
@Input() id;
that;
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);
}
所以问题是它第一次不起作用,但之后它确实有效 .
2 回答
当您检索人员列表(异步)时,获取特定人员的代码已经执行并返回null .
那么..您可以在人员列表的订阅处理程序中更新特定人员的代码,或者让人们在ngOnInit上进行检索,并在按钮点击或ngAfterViewInit()上进行人员检索 .
理想情况下,人员列表检索应该在服务自己的初始化(更好)中进行,或者可以通过直接链接两个请求来完成特定的人员搜索(从http获取人员列表并在成功处理程序中搜索id);虽然它会重复http调用(因此不是那么理想) .
实现不正确,可以更简单地看看以下解决方案:
service
service