Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 按id的角度过滤器数据_Angular_Typescript - Fatal编程技术网

Angular 按id的角度过滤器数据

Angular 按id的角度过滤器数据,angular,typescript,Angular,Typescript,我有一个角度项目中的一些数据,我想用它来代替数据库,因为它的数据非常少…大约50个id,有5个字段…以下是数据: mydata = [ { "id": 3, "active": 1, "title": "Title 1", "text": "this is some text from 3" }, { "id": 31, "active": 1, "title": "Title 1", "text": "this is

我有一个角度项目中的一些数据,我想用它来代替数据库,因为它的数据非常少…大约50个id,有5个字段…以下是数据:

mydata = [

  {
    "id": 3,
    "active": 1,
    "title": "Title 1",
    "text": "this is some text from 3"
  },
  {
    "id": 31,
    "active": 1,
    "title": "Title 1",
    "text": "this is some text from 31"
  },
  {
    "id": 11,
    "active": 1,
    "title": "Title 1",
    "text": "this is some text for 11"
  },
  {
    "id": 21,
    "active": 1,
    "title": "Title 1",
    "text": "this is some text from 21"
  }

]
然后我有一个方法:

getDataText(id) {
    // code to get the text of the data with the selected id
    // do it should get me the data (in this case the text from id 11) 
}
然后在component.html文件中,我有:

<button (click)="getDataText(11)">Get Data by Id</button>
按Id获取数据
我该怎么做?

试试这个:

getDataText(id) {
    let findedData = this.myData.find(i => i.id === id);
    if (typeof findedData === 'undefined') {
       return null;
    }
    return findedData;
} 
注意,如果在条件中未找到任何内容,则结果将是未定义的

这必须起作用:

getDataText(id){
const result=this.mydata.filter(x=>x.id==id);
返回结果;

}

您的
getDataText
应该如下所示:

getDataText(id) {
  const data = myData.find(x => x.id === id);
  return data ? data.text : `Cannot find data with id ${id}`;
}
您甚至可以分为两种方法:

getDataById(id) {
  return myData.find(x => x.id === id);
}

getDataText(id) {
  const data = this.getDataById(id);
  return data ? data.text : `Cannot find data with id ${id}`;
}
这将返回具有给定id的项的文本,如果没有具有给定id的项,则返回未定义的文本。

public result=“按id获取数据”;
public result = "Get Data by Id";
public getDataText(id) {
  const reqObj = this.mydata.find(item => item.id === id);
  this.result = reqObj ? reqObj.text : 'nothing found';
}


<button (click)="getDataText(11)">{{result})</button>
公共getDataText(id){ const reqObj=this.mydata.find(item=>item.id==id); this.result=reqObj?reqObj.text:'未找到'; } {{result})

这里您可以看到my

保留一个额外的数组,该数组保存过滤后的数据您可以使用filter操作符:this.mydata.filter(x=>x.id==11)
public result = "Get Data by Id";
public getDataText(id) {
  const reqObj = this.mydata.find(item => item.id === id);
  this.result = reqObj ? reqObj.text : 'nothing found';
}


<button (click)="getDataText(11)">{{result})</button>