过滤器参数需要在 Angular2 中输入

在将数据分配给我的角度组件之前尝试过滤数组时遇到了一些问题,我有一个提示数组,但我最初只想显示 1 个提示

我的问题是,当我尝试通过匹配 ID 1 的提示过滤我的数组时,我不断收到

"'hint' 隐式具有 'any' 类型。"在 cli 中,但这应该没问题,因为它只是一个计数器

我在我的 tsconfig.json 中禁用了字符串注入参数,并遵循了其他各种关于禁用严格的打字稿注入规则的帖子,但我无法停止向我询问计数器的类型,因此我无法使用过滤器功能这里

import { Component,Input,OnInit } from '@angular/core';
import { SpecsService } from 'src/app/specs.service';
import {Hint} from './hint';

@Component({
  selector: 'app-hintbox',templateUrl: './hintbox.component.html',styleUrls: ['./hintbox.component.css']
})

export class HintboxComponent implements OnInit {
 currentHint: Hint[]=[]
 hint: Hint={hint:'',id:0}
 
  constructor(private specsService: SpecsService) { }
  ngOnInit(): void {

    this.specsService.getHints().subscribe((response)=> this.currentHint= response.filter(hint:Hint => hint.id===1));   
  }

}

下面是我的响应对象的图像

过滤器参数需要在 Angular2 中输入

希望得到任何建议,或者如果以后有更合理的方法来过滤数据那将是惊人的

这是我的规范服务功能,它指向我的虚拟 json 服务器

export class SpecsService {
  private apiUrl = 'http://localhost:3000'
  constructor(private http:HttpClient) {}


  getHints(): Observable<any>{
    return this.http.get(`${this.apiUrl}/Hints`)
  }
}
zqplyn1234 回答:过滤器参数需要在 Angular2 中输入

把我的头放在你的代码上有点令人困惑。我从来没有在我的代码中使用 JSON.stringify() -- Angular HTTPClientModule 已经将结果转换为 JSON。

但是,一般来说,为该类型创建一个类:

export class Hint {
   id: number,otherprop: string
}

您的转换代码可以强输入:

this.specsService.getHints().subscribe((response)=> this.currentHint= response.filter(hint: Hint => hint.id===1));
,

您的 getHints() 函数返回 Object 类型的 Observable。这就是为什么每当您尝试分配它时都会返回未知类型的原因。一个简单的解决方案来检查是否是这种情况,请尝试以下


  getHints() {
    return this.http.get<any>(`${this.apiUrl}/Hints`)
  }

有了上述,错误就会消失,但这可能不是最好的做法。

因此,要以更好的方式解决您的问题,请理解预期的对象并输入您的响应

从您的代码来看,您似乎收到了一系列项目,因此您可以拥有以下内容


interface IHintResponse {
  id:  number;
  // Other props here
}

  getHints() {
    return this.http.get<IHintResponse[]>(`${this.apiUrl}/Hints`)
  }
本文链接:https://www.f2er.com/3833.html

大家都在问