I am getting this error with my component not sure what to do?
here is the component:
import { Component, OnInit } from \'@angular/core\';
import { H
Now that we have the data structure:
[
{
"pk": "wGR",
"created": "2017-10-07T01:42:25.110747Z",
"email_domain": "domain.com",
"sender_name": null,
"sender_email": "user@domain.com",
"has_user_viewed": false,
"is_shielded": false
}
]
you should probably create an interface like this:
interface ItemsResponse {
pk: string;
created: string;
email_domain: string;
sender_name: string;
sender_email: string;
has_user_viewed: boolean;
is_shielded: boolean;
}
and change the definition of results to results: ItemsResponse[].
That means that this.results will be an array, each element being an ItemsResponse object.
After the request completes, you'll be able to access it as you would expect:
this.results[0]["sender_email"]
this.results[12]["pk"]
this.results.map(item => console.log(item.pk))
and so on.
Note that in my interface I have used just string for the pk field, but if you have a limited set of possible values, like "wGR", "wGA", "wGP" you can use a string enum type like so:
interface ItemsResponse {
pk: "wGR" | "wGA" | "wGP";
// ...
}
To explicitly explain why you had the error, however, you cannot cast an ItemsResponse to a string[], which is what you were doing by asserting the response of your get request as (doing this tells the typechecker that data will be an ItemsResponse), but you then assign it to this.results, which you have declared as a string[]. Hopefully the illustration above shows why this won't work.
You have a type interface which defines a field called results:
interface ItemsResponse {
results: string[];
}
In your service, you cast email_list.json to :
this.http.get('assets/api/email_list.json').subscribe(data => {
this.results = data;
console.log(this.results);
});
which means it expects email_list.json to look like this:
{
"results": [
"one@example.com",
"two@example.com"
]
}
while it's likely actually
[
"one@example.com",
"two@example.com"
]
So you need to either
this.results = data.results, orstring[]