admin管理员组文章数量:1415109
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
3 Answers
Reset to default 3Error "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)
本文标签: javascriptHow do I automatically run a function when the page is loadedStack Overflow
版权声明:本文标题:javascript - How do I automatically run a function when the page is loaded? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745197549a2647215.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论