繁体   English   中英

加载页面时如何自动运行 function?

[英]How do I automatically run a function when the page is loaded?

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

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

我已经尝试在 component.ts 文件的 ngOnInit() 中插入 function:

ngOnInit(){
    this.getData()
  }

并尝试在 component.html 文件中加载:

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

...两者都没有导致所需的结果

这就是代码的样子(我基本上从 API 调用和 select 一个具有特定 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()
  }

组件.html

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

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

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

我怎样才能让它自动发生?

错误“无法读取未定义的属性‘标题’”

这是因为当表达式在模板中运行时,那时数据还没有加载,它是未定义的。

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

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

当您要调用方法 onload 时, ngOnInit()是正确的位置。 如果数据是异步的,则在呈现模板时仍然可以未定义“已选择”。 为避免该错误,您可以使用 @Flignats 之类的条件包装块,或者简单地添加一个? 喜欢

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

?. selected时停止评估是nullundefined

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

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);
  });
}

使用$scope并在 controller 的开头调用 function,就像这样

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

$scope.init();

controller是随页面自动加载的,这种情况下的$scope可以做你想要的(不包装在其他函数中会自动调用$scope.init())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM