Angular5 HttpClient 在组件视图中返回未定义
Angular5 HttpClient returning undefined in component view
我正在尝试访问一个 API 那个 returns 一个 JSON 和一些数据然后我需要通过使用 ngFor
因为它是一个对象。在 http.get
函数中,如果我 console.log
返回数据,它看起来很好。但是当我尝试在我的视图中呈现它时,它不起作用。
这是我的 component.ts:
import { HttpClient } from '@angular/common/http';
export class AnonimoComponent implements OnInit {
public medicamentos: Object;
private baseURL = 'http://website.com/api/medicamentos';
constructor(private http: HttpClient) { }
ngOnInit() {
this.getMedicamentos();
}
getMedicamentos(){
interface MedicamentoResponse {
id: number;
Name: string;
Preco: number;
}
this.http.get<MedicamentoResponse>(this.baseURL).subscribe((data) => {
this.medicamentos = data;
console.log("First:\n" + this.medicamentos);
});
}
}
这是我的 html:
<ul>
<li *ngFor="let med of medicamentos$ | async">
{{med}}
</li>
</ul>
但是,它没有显示任何内容。有什么想法吗?
*ngFor 不适用于 JSON..
您必须将其转换为数组。
试试这个
this.medicamentos = data.json();
改变
*ngFor="let med of medicamentos$ | async"
至
*ngFor="let med of medicamentos"
- 你不能使用
async
因为 medicamentos
不是 Observable,你直接在组件代码 subscribe
中分配了结果
- 大小写和变量名很重要,您不能在模板中的变量名末尾添加
$
这样的字符并让它仍然有效。
最后,您应该验证分配给 medicamentos
的实际上是一个数组,验证浏览器调试器中的响应。
如果使用|async
管道,则不能使用.subscribe()
。
应该是
getMedicamentos(){
this.medicamentos = this.http.get<MedicamentoResponse>(this.baseURL);
}
如果你使用
this.medicamentos = data;
那你就不需要|async
我正在尝试访问一个 API 那个 returns 一个 JSON 和一些数据然后我需要通过使用 ngFor
因为它是一个对象。在 http.get
函数中,如果我 console.log
返回数据,它看起来很好。但是当我尝试在我的视图中呈现它时,它不起作用。
这是我的 component.ts:
import { HttpClient } from '@angular/common/http';
export class AnonimoComponent implements OnInit {
public medicamentos: Object;
private baseURL = 'http://website.com/api/medicamentos';
constructor(private http: HttpClient) { }
ngOnInit() {
this.getMedicamentos();
}
getMedicamentos(){
interface MedicamentoResponse {
id: number;
Name: string;
Preco: number;
}
this.http.get<MedicamentoResponse>(this.baseURL).subscribe((data) => {
this.medicamentos = data;
console.log("First:\n" + this.medicamentos);
});
}
}
这是我的 html:
<ul>
<li *ngFor="let med of medicamentos$ | async">
{{med}}
</li>
</ul>
但是,它没有显示任何内容。有什么想法吗?
*ngFor 不适用于 JSON..
您必须将其转换为数组。
试试这个
this.medicamentos = data.json();
改变
*ngFor="let med of medicamentos$ | async"
至
*ngFor="let med of medicamentos"
- 你不能使用
async
因为medicamentos
不是 Observable,你直接在组件代码subscribe
中分配了结果 - 大小写和变量名很重要,您不能在模板中的变量名末尾添加
$
这样的字符并让它仍然有效。
最后,您应该验证分配给 medicamentos
的实际上是一个数组,验证浏览器调试器中的响应。
如果使用|async
管道,则不能使用.subscribe()
。
应该是
getMedicamentos(){
this.medicamentos = this.http.get<MedicamentoResponse>(this.baseURL);
}
如果你使用
this.medicamentos = data;
那你就不需要|async