Javascript 错误类型错误:data.slice 不是函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51304884/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:48:41  来源:igfitidea点击:

ERROR TypeError: data.slice is not a function

javascriptangular

提问by Basha

ERROR TypeError: data.slice is not a function
#atMatTableDataSource.push../node_modules/@angular/material/esm5/table.es5.js.MatTableDataSource._orderData (table.es5.js:742)

#at MapSubscriber.project (table.es5.js:675)
#atMapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/map.js.MapSubscriber._next (map.js:35)
#atMapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:54)

I am consuming a JSON response and attempting to display it in the UI through angular material mat-table. please find the attached snippet of code and let me know what is the mistake in the code which I have made or do I need to change my approach to achieve this

我正在使用 JSON 响应并尝试通过有角度的材料垫表在 UI 中显示它。请找到随附的代码片段,让我知道我所做的代码中有什么错误,或者我是否需要改变我的方法来实现这一目标

JSON webservice

JSON 网络服务

{
"data": [
{
  "action": "Ok",
  "created_user": "slstst5",
  "latest_instance": 7713997,
  "modified_dt": "Thu, 12 Jul 2018 06:27:32 GMT",
  "no_of_btl": 159,
  "request": 238244193,
  "sales_rep": "slstst5",
  "status_cd": "Submitted to Prov."
},

Service.ts

服务.ts

import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {sot} from './sot.model';
import { Observable } from "rxjs";

@Injectable({
providedIn: 'root'
})
export class SotServiceService {
private serviceUrl ="service URL";

constructor(private http : HttpClient) { }
getuser():Observable<sot[]>{
  return this.http.get<sot[]>(this.serviceUrl);
}
}

table.component.ts

table.component.ts

import { Component, OnInit, ViewChild } from '@angular/core';
import { Observable } from "rxjs";
import {MatSort, MatSortable, MatTableDataSource,PageEvent, MatPaginator} 
from '@angular/material';
import {SotServiceService} from '../sot-service.service';

@Component({
selector: 'app-sot-table',
templateUrl: './sot-table.component.html',
styleUrls: ['./sot-table.component.css']
})
export class SotTableComponent implements OnInit {
@ViewChild(MatSort) sort: MatSort;
@ViewChild(MatPaginator) paginator : MatPaginator;
dataSource;
//displayedColumns = ['id', 'name', 'username', 'email', 'phone', 'website'];
displayedColumns = ['request', 'status_cd', 'sales_rep', 'created_user', 
'modified_dt', 'action','no_of_btl'];
//displayedColumns=['userId','id','title','body']
constructor(private sotservice :SotServiceService) { }

ngOnInit() {
this.sotservice.getuser().subscribe(result => {

  if(!result){
    return ;
  }
  this.dataSource= new MatTableDataSource(result);
  this.dataSource.sort= this.sort;
  this.dataSource.paginator=this.paginator;
 })
 }

}

Error snapshot: Error Snapshot

错误快照: 错误快照

回答by Wesley Coetzee

Your dataobject is inside of the resultobject. You will need to do the following:

您的data对象在对象内部result。您需要执行以下操作:

ngOnInit() {
  this.sotservice.getuser()
    .subscribe(result => {
      if(!result){
        return;
      }

      this.dataSource= new MatTableDataSource(result.data);
      this.dataSource.sort= this.sort;
      this.dataSource.paginator=this.paginator;
  });
}

回答by Shrey Tiwari

This happens sometimes when you are using the slice function on wrong data type. Slice works on an array, not an object. It might happen that you are trying to slice an object.

当您在错误的数据类型上使用 slice 函数时,有时会发生这种情况。Slice 作用于数组,而不是对象。您可能会尝试切片对象。

回答by Saqib Raja

This error is due to the array returned by your webservice. result contains the array of data. To avoid data.slice is not a function error, you will need to point your result to result.data as mentioned by Wesley Coetzee. You can safely remove observable from the service as well. If you are not sure about the Sot object, replace it with any or remove it

此错误是由于您的网络服务返回的数组造成的。结果包含数据数组。为了避免 data.slice 不是函数错误,您需要将结果指向 result.data,如 Wesley Coetzee 所述。您也可以安全地从服务中删除 observable。如果您不确定 Sot 对象,请将其替换为 any 或将其删除

P.S. This error also occurs if you have sub-array in result.data as well. In that case you will do something like, this.dataSource = new MatTableDataSource(res.data.yourSubArray);

PS 如果您在 result.data 中也有子数组,也会发生此错误。在这种情况下,您将执行以下操作: this.dataSource = new MatTableDataSource(res.data.yourSubArray);

回答by Ronny Mahlangu

Please try change this line this.dataSource = new MatTableDataSource(result);to this.datasource.result = results['Data']then have your dataSource initialized just outside of your constructor like dataSource = new MatTableDataSource();

请尝试更改此行this.dataSource = new MatTableDataSource(result);this.datasource.result = results['Data']然后在构造函数之外初始化您的数据源,例如dataSource = new MatTableDataSource();

What you'll basically doing here is to tell your code that there is an element named Data in my result so give me the value or data of this element and assign it to my data-source, hope it helps, had the similar issue and this is how I resolved it

你在这里基本上要做的是告诉你的代码在我的结果中有一个名为 Data 的元素,所以给我这个元素的值或数据并将它分配给我的数据源,希望它有帮助,有类似的问题和这就是我解决它的方法

回答by Sagar Jauhri

You Should use

你应该使用

this.dataSource = new MatTableDataSource(result.data);

Because there is a key named as 'data' in your json file which contain array of your data object.

因为在包含数据对象数组的 json 文件中有一个名为 'data' 的键。

回答by T. Bulford

My observable stream returns data from local indexedDB storage (no backend), and my mistake was not checking array length of the stream parameter before assigning it to MatTableDataSource, which resulted in the same type error. Here is my fix:

我的可观察流从本地 indexedDB 存储(无后端)返回数据,我的错误是在将其分配给 MatTableDataSource 之前没有检查流参数的数组长度,这导致了相同类型的错误。这是我的修复:

ngOnInit() {
   this.dataStream = this.storageService.getDataStream().subscribe((activeDataList: any) => { 
      if (activeDataList.length) { 
         this.dataSource = new MatTableDataSource(activeDataList);
      }
   });
}

回答by Brian Sanchez

just make sure data is an array / list of your expected data for the table, otherwise won't be possible to slice.

只需确保数据是表的预期数据的数组/列表,否则将无法切片。

simple

简单的