Reputation: 469
I'm having some trouble trying to filter an array before assigning the data to my angular component, I have an array of hints but I only want to display 1 hint initially
my problem is that when I try to filter my array by a hint that matches the ID of 1 I keep getting
"'hint' implicitly has an 'any' type." in the cli but this should be fine as its just a counter
I have disabled string injection params in my tsconfig.json and followed various other posts about disabling strict typescript injection rules but I can't get angular to quit asking me for a type for the counter, thus I cannot use the filter function here
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));
}
}
below is an image of my response object
hoping for any advice, or if there is a more reasonable way to filter the data later that would be amazing
here is my specs service function, its pointed at my dummy json server
export class SpecsService {
private apiUrl = 'http://localhost:3000'
constructor(private http:HttpClient) {}
getHints(): Observable<any>{
return this.http.get(`${this.apiUrl}/Hints`)
}
}
Upvotes: 1
Views: 386
Reputation: 15083
Your getHints()
function returns an Observable of type Object
. That is why whenever you try to assign it returns an unknown type. A simple solution to check that this is the case try below
getHints() {
return this.http.get<any>(`${this.apiUrl}/Hints`)
}
With the above, the error will go away but this may not be the best course of action.
So to solve your problem in a better way would be to understand the expected object and type your response
From your code it looks like you are receiving back an array of items so you can have something like below
interface IHintResponse {
id: number;
// Other props here
}
getHints() {
return this.http.get<IHintResponse[]>(`${this.apiUrl}/Hints`)
}
Upvotes: 1
Reputation: 39408
It is kind of confusing to wrap my head around your code. I don't use JSON.stringify()
in my code ever--Angular HTTPClientModule
will already convert the results to JSON.
But, generically, create a class for the type:
export class Hint {
id: number,
otherprop: string
}
Your conversion code can strongly type:
this.specsService.getHints().subscribe((response)=> this.currentHint= response.filter(hint: Hint => hint.id===1));
Upvotes: 1