简体   繁体   中英

How to split data array in Angular Service?

I have data form as below

{
  "COLUMNS": ["Col1", "Col2", "Col3", "Col4", "Col5"],

  "DATA": [
             [Test, Test, Test, Test, Test],
             [Test, Test, Test, Test, Test]
          ]
}

I want to split this data two pieces in my service and i want to get my columns and data seperate.

I try to use .shift() method as below but it's return undefined.

My service:

getService(): any{
 this.http.get<string[]>(this.url2).pipe(map(data => {
  return data.shift()
}))

}

My component:

  ngOnInit(): void {
      this.columns = this.productService.getProductsService();
  }

What am i doing wrong?

You are returning an Observable in the getService() , you should subscribe to it to get the result first and then do whatever you want.

First of all you should not use the ngOnInit lifecycle hook to load data.

Secondly, according to your types you expect an array of strings string[] , but say that you want to split another data structure if I understood your inquiry correctly. array.shift() removes the first element from the array and returns it. When you shift string[] you get a string but you say that the intention is to split an object.

{
  "COLUMNS": ["Col1", "Col2", "Col3", "Col4", "Col5"],

  "DATA": [
             [Test, Test, Test, Test, Test],
             [Test, Test, Test, Test, Test]
          ]
}

^ this one will be something like { COLUMNS: string[], DATA: Test[][] }

Thirdly, what is the Test type?

...
[
  [Test, Test, Test, Test, Test],
  [Test, Test, Test, Test, Test]
]
...

Fourthly, you should not use any .

Finally, my suggestion is to fix types first. Then use SOLID. The http-service should only request data and return it as is. That's it, no mutations, no side effects. Splitting the received data is not the http-service responsibility obviously.

I fixed my problem. Here my solution

public general : any[];
public columns : string[];
public gridData: Test[];

this.productService.getProductsService().subscribe((res: Test[]) => {
  this.general = res;
  this.columns = Object.values(this.general).shift();
  this.gridData = Object.values(this.general)[1];
  
});

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