最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I automatically run a function when the page is loaded? - Stack Overflow

programmeradmin1浏览0评论

I have a function called "getData" that needs to be executed in order to display certain information. I want it to run automatically but at the moment it only displays the data after clicking a button that activates the function - see (ponent.html):

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

I already tried to insert the function in ngOnInit() in the ponent.ts-file:

ngOnInit(){
    this.getData()
  }

and tried onload in the ponent.html file:

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

... both did not lead to the needed result

This is how the code looks like (I basically get the data from an API Call and select an item with a certain id) ponent.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()
  }

ponent.html

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

When loading the page the console logs the following Error "Cannot read property 'title' of undefined" and the error message refers to this line: <h1>{{selected.title}}</h1>

But when I click the button it logs the data as it is supposed to.

How can I let this automatically happen?

I have a function called "getData" that needs to be executed in order to display certain information. I want it to run automatically but at the moment it only displays the data after clicking a button that activates the function - see (ponent.html):

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

I already tried to insert the function in ngOnInit() in the ponent.ts-file:

ngOnInit(){
    this.getData()
  }

and tried onload in the ponent.html file:

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

... both did not lead to the needed result

This is how the code looks like (I basically get the data from an API Call and select an item with a certain id) ponent.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()
  }

ponent.html

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

When loading the page the console logs the following Error "Cannot read property 'title' of undefined" and the error message refers to this line: <h1>{{selected.title}}</h1>

But when I click the button it logs the data as it is supposed to.

How can I let this automatically happen?

Share Improve this question edited Oct 28, 2019 at 15:04 asked Oct 28, 2019 at 14:34 user11962606user11962606 6
  • I'm not familiar with angular. How do you pass the data to the template engine? – Adder Commented Oct 28, 2019 at 14:40
  • @mplungjan While there are questions related to loading data before rendering in angular all/most of those results are for anuglarjs, personally I hate the angular tab as there are now so many versions, it's hard to tell which one someone is using – George Commented Oct 28, 2019 at 14:41
  • @George then something like stackoverflow./search?q=%5Bangular%5D+execute+page+load – mplungjan Commented Oct 28, 2019 at 14:43
  • 1 You'd need to post more code. You're initializing selected to an array [] but trying to access an object. – Flignats Commented Oct 28, 2019 at 15:00
  • @Flignats: thanks for the advice - added further code above – user11962606 Commented Oct 28, 2019 at 15:05
 |  Show 1 more ment

3 Answers 3

Reset to default 3

Error "Cannot read property 'title' of undefined"

This is because when the expression is ran in the template, at that time the data has not loaded and it is undefined.

Put the call back into the ngOnInit() and wrap the expression in an ngIf statement.

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

ngOnInit() is the right place, when you want to call the method onload. If the data is async 'selected' can still be undefined when the template is rendered. To avoid the error you can wrap the block with a condition like @Flignats did or simply add a ? like

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

The ?. stops evaluating when selected is null or undefined.

You are assigning the data outside the subscription. It should be like this:

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

Use $scope and call a function at the beginning of your controller, like this

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

$scope.init();

The controller is automatically loaded with the page, and the $scope in this case can make what you want ($scope.init() is automatically called if you don't wrap it in other functions)

发布评论

评论列表(0)

  1. 暂无评论