Home > Net >  How to split data array in Angular Service?
How to split data array in Angular Service?

Time:12-26

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?

CodePudding user response:

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

Example:

this.productService.getProductsService().subscribe(c => {
  this.columns = c;
});

Also, you should correct the name of the method that you are trying to call from the service : getProductsService() or getService()

CodePudding user response:

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.

  • Related