简体   繁体   中英

Get the object of an Observable and convert to Array with Angular

Good Morning.

I am getting the following object and need to work with the data in the results (Array) but my my method does not working properly.

Object
currentPage: 1
firstRowOnPage: 1
lastRowOnPage: 6
pageCount: 1
pageSize: 10
results: Array(6)
0: {id: 1256, name: "Erik", address: "Centro", addressComplement: "Centro", cep: "11212-122", …}
1: {id: 1014, name: "Everson Luiz", address: null, addressComplement: null, cep: null, …}
2: {id: 1011, name: "Everson Luiz Silva", address: null, addressComplement: null, cep: null, …}
3: {id: 1284, name: "Fulado de Tal", address: null, addressComplement: null, cep: null, …}
4: {id: 1012, name: "Jackson Alexandre", address: null, addressComplement: null, cep: null, …}
5: {id: 1013, name: "Robson Henrique Silva", address: "", addressComplement: "", cep: "", …}
length: 6
__proto__: Array(0)
rowCount: 6
__proto__: Object

When I try to access the data, I get an error stating that my object is not an array so it does not have the typical methods of an array like MAP and PUSH POP FILTER.

This is my object and this is my method.

  private dataStore = {
    treasurers: []
  };

  private loadAllTreasurers(): void {
    const unit = auth.getCurrentUnit();
    this.treasureService.getTreasurers(unit.id).subscribe((data: Treasurer[]) => {
      console.log(data)
      this.dataStore.treasurers = data;
    });
 }


<!--Service-->

 getTreasurers(unitId): Observable<Treasurer[]> {
    const url = '/treasury/treasurers/unit/' + unitId;
    return this.http
      .get<Treasurer[]>(url);
  }

I get the object from an AspnetCore 2.2 server

Your problem is that your Array isn't the data object. It's in data.results . data looks like an object with pages response info. You want data.results and not the data object.

You should just need to update this:

this.treasureService.getTreasurers(unit.id).subscribe((data: object) => {
  console.log(data)
  this.dataStore.treasurers = data.results; // <-- .results
});

I'm not sure if your data object has a Type or not, so I set it to object as a placeholder

Thanks for trying.

But it still doesn't run. The error persists in the DATA object. He tells me that he does not have the RESULT property.

I managed to solve it this wayI managed to solve this way using TAP:

this.treasurerService
      .getTreasurers(id)
      .pipe(
        tap(data => {                
            this.dataStore.treasurers = data.results;
          })
      );

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