加载页面后如何自动运行功能?

问题描述 投票:1回答:3

我有一个名为“ getData”的函数,需要执行该函数才能显示某些信息。我希望它自动运行,但此刻它仅在单击激活该功能的按钮后才显示数据-请参阅(component.html):

<button (click)="getData()">Fetch Data</button>

我已经尝试在component.ts-file的ngOnInit()中插入函数:

ngOnInit(){
    this.getData()
  }

并尝试在component.html文件中进行onload:

<p onload="getData();">component works!</p>

...两者均未导致所需的结果

这是代码的样子(我基本上是从API调用中获取数据,然后选择具有特定ID的项目)component.ts

/*some code*/
export class DetailComponent implements OnInit {
  public data: any = []
  public selected: any = []
  constructor(
    public http: HttpClient, 
    public route: ActivatedRoute) { }

  getData(){
    const person_id = this.route.snapshot.paramMap.get('person_id');
    const url ='http://localhost:4000/api/allpeople';
    this.http.get(url).subscribe(data => this.data = data);
    this.selected=this.data.find(item=>
      {
        if(item['person_id']===person_id)
          {
            return true;
          }
        return false;
      });
    console.log(person_id, this.selected);
    return this.selected;
  }

  ngOnInit(){
    this.getData()
  }

component.html

<h1>{{selected.title}}</h1>
{{selected.person_id}}

加载页面时,控制台记录以下错误“无法读取未定义的属性'title'”并且错误消息指向此行:<h1>{{selected.title}}</h1>

但是当我单击按钮时,它会按预期记录数据。

我如何让这种情况自动发生?

javascript html angular function onload
3个回答
4
投票

错误“无法读取未定义的属性'title'”

这是因为当在模板中运行表达式时,当时数据尚未加载并且未定义。

将调用放回ngOnInit(),并将表达式包装在ngIf语句中。

<ng-container *ngIf="selected">
  <h1>{{selected.title}}</h1>
  {{selected.person_id}}
</ng-container>

0
投票

使用$scope并在控制器的开头调用一个函数,像这样

$scope.init = function () {
   $scope.title = "title";
   $scope.person_id = 2;
};

$scope.init();

控制器会自动加载页面,在这种情况下,$ scope可以满足您的要求(如果不将其包装在其他函数中,则会自动调用$ scope.init()]


0
投票
当您要调用方法onload时,

ngOnInit()是正确的位置。如果数据是异步的,则在渲染模板时仍无法定义“已选择”。为了避免该错误,您可以使用类似于@Flignats的条件来包装该块,或者只需添加一个?这样的条件

  <h1>{{selected?.title}}</h1>
  {{selected?.person_id}}

?.selectednullundefined停止评估。

您正在订阅之外分配数据。应该是这样的:

getData(){
...
this.http.get(url).subscribe(data => {
  this.data = data;
  this.selected=this.data.find(item=>
    {
      if(item['person_id']===person_id)
        {
          return true;
        }
      return false;
    });
    console.log(person_id, this.selected);
  });
}
© www.soinside.com 2019 - 2024. All rights reserved.