简体   繁体   中英

How to get data from json in Angular2

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>

loadStudents() returns a Promise. So in your component the code has to be like:

 ngOnInit(){
       this.studentService.loadStudents()
           .then((students) => {
               this.studdata = students;
           });
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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