Reputation: 1041
I have a Json response like this.
{
"response": {
"my_students": {
"students": [
{
"studentNumber": "123",
"studentName": "ABC"
"studentaddresse": [
{
"address": "test"
}
]
},
{
"studentNumber": "345",
"studentName": "CDS"
"studentaddresse": [
{
"address": "test1"
}
]
}
]
}
}
}
On button click I have to fetch these data. For that In component.ts file I have this code
studdata=[];
ngOnInit(){
this.studdata= this.studentService.loadStudents();
}
And in student.service.ts file I have this code
loadStudents(): any{
return this.loginService.getStudentData();
}
And in login.Service.ts file I have this code //On button click i am calling getStudentResponseData() this method In console am getting data.but in getStudentData() method am not getting data
student_data: Object;
public getStudentResponseData() : Promise<any> {
if(typeof(this.student_data) === "undefined") {
return this.http.get('assets/studentapi.json')
.toPromise().then(res => {
this.student_data = res.json().response;
console.log("data"+this.student_data);
return this.student_data;
}).catch(this.handleError);
} else {
return Promise.resolve(this.student_data);
}
}
public getStudentData(): Object {
return this.student_data;
}
Can anyone please help me with this,where i am doing wrong? And I want to display values in html ,How to display student number here.
<div *ngFor="let stu of studdata">
<div>{{stu.studentNumber}}</div>
</div>
Upvotes: 2
Views: 65
Reputation: 17808
loadStudents()
returns a Promise. So in your component the code has to be like:
ngOnInit(){
this.studentService.loadStudents()
.then((students) => {
this.studdata = students;
});
}
Upvotes: 2
Reputation: 75
Because this method is async. You can get the data in .Promise().then ( ... you can handle data here ...)
You can not get data from getStudentData()
function because of that async of method.
Upvotes: 1