javascript - Angular HttpClient cómo pasar resultados a la plantilla
Soy nuevo en Angular y estoy COMPLETAMENTE perdiéndome de algo aquí. He configurado un componente para hacer una solicitud GET siguiendo la documentación y con algo de ayuda de una publicación anterior aquí :) Ahora me falta cómo pasar los resultados a la plantilla.
Este es mi componente:
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-emails',
templateUrl: './emails.component.html',
styleUrls: ['./emails.component.scss']
})
export class EmailsComponent implements OnInit {
test = 'test';
results: string[];
constructor(private http: HttpClient) { }
ngOnInit() {
interface ItemsResponse {
results: string[];
}
this.http.get<ItemsResponse>('assets/api/email_list.json').subscribe(data => {
this.results = data['results'];
console.log(this.results);
});
}
}
y mi plantilla es bastante simple:
<p>results</p>
<p>{{test}}</p>
<p>
{{results}}
</p>
¡Parece que hacer la transición de aprender AngularJS a Angular me está haciendo darme cabezazos contra la pared aquí!
Formato JSON:
[
{
"pk": "wGR",
"created": "2017-10-07T01:42:25.110747Z",
"email_domain": "domain.com",
"sender_name": null,
"sender_email": "[email ",
"has_user_viewed": false,
"is_shielded": false
}
]
Respuesta #1
Intenta así :
export class EmailsComponent implements OnInit {
test = 'test';
results: Array<string> = [];
constructor(private http: HttpClient) { }
ngOnInit() {
interface ItemsResponse {
results: string[];
}
this.http.get<ItemsResponse>('assets/api/email_list.json').subscribe(data => {
this.results = data.json();
console.log(this.results);
});
}
}
