Home > Back-end >  Unable to loop the api data in angular
Unable to loop the api data in angular

Time:08-21

I have API response as below. Click to see image API : { "isSuccess": true, "message": "Data fetched successfully", "data": [ { "id": "62fed72c775efbb8b1746587", "createdDate": "19-08-2022 05:49:56", "updatedDate": "", "firstName": "Harika", "lastName": "Ramesh", "age": 27, "contact": "987t65767", "salary": 150000, "message": null }, { "id": "62fed8b3c601d740feea86c7", "createdDate": "19-08-2022 05:56:18", "updatedDate": "", "firstName": "Hari", "lastName": "Kesh", "age": 28, "contact": "456789900", "salary": 987654, "message": null }, { "id": "62fedb5c05399d26b492f42e", "createdDate": "19-08-2022 06:07:44", "updatedDate": "", "firstName": "Ram", "lastName": "D", "age": 29, "contact": "9876543", "salary": 1500000, "message": null } ] }

But in angular return response how to pass only array data that i can loop I am not sure since I am new to angular. Following are some code

crudOp.model.ts file
export interface crudOp {
    Id:string;
    CreatedDate:string;
    UpdatedDate:string;
    FirstName:string;
    LastName:string;
    Age:number;
    Contact:number;
    Salary:number;
    Message:string;
}



crud-mongo.service.ts
export class CrudMongoService { 
  baseUrl = "https://localhost:44391/api/CrudOperations";

  constructor(private http: HttpClient) { }
  GetAllRecord(): Observable<crudOp[]>{
    return this.http.get<crudOp[]>(this.baseUrl   '/GetAllRecord');

  }
}



app.component.ts file 
export class AppComponent implements OnInit{
  title = 'CrudMongo';
  crudlist:crudOp[] =[];

  constructor(private crudMongoService :CrudMongoService){

  }
  ngOnInit(): void{
    this.GetAllRecord();
  }

  GetAllRecord(){
    this.crudMongoService.GetAllRecord()
    .subscribe(
      response => {
        // console.log(Object.values(response)[2]);
        console.log(response);
        this.crudlist = response;
      });
  }
}

I want to loop the "data" array

CodePudding user response:

so you just need to check does the response have data or not and assign data to your array. below I modified GetAllRecord method.

app.component.ts file

 GetAllRecord(){
    this.crudMongoService.GetAllRecord()
    .subscribe(response: any => {
        console.log(response);
        this.crudlist = response && response.data ? response.data : [];
     });
  }

Changed the return type in the service file, because API not returning the type of data that you mentioned for the service method. edited your code.

export class CrudMongoService { 
  baseUrl = "https://localhost:44391/api/CrudOperations";

  constructor(private http: HttpClient) { }
  GetAllRecord() {
    return this.http.get(this.baseUrl   '/GetAllRecord');

  }
}
  • Related