angular - 将 Json 数据检索到 ITest
问题描述
目标:
从json中获取数据到“test: ITest[];” 然后使用 console.log 显示它
问题:
代码不起作用。我错过了什么?
信息:
我是 Angular 的新手
谢谢!
服务
getData2(): Observable<ITest[]> {
return this.http.get<ITest[]>('https://api.github.com/users/hadley/orgs');
}
export interface ITest {
login: string,
node_id: string
}
零件
public test: ITest[];
ngOnInit() {
this.getData2()
}
getData2() {
this.asdfService.getData2().subscribe(res => { this.test = res });
console.log(this.test)
};
export interface ITest {
login: string,
node_id: string
}
解决方案
你的方法getData2
返回一个 Observable,它可能会在一段时间后被解析,但console.log
调用是在 之后subscribe
,所以当console.log
被调用时,Observable 可能还没有解析。
试试这个:
getData2() {
this.asdfService.getData2().subscribe(res => {
this.test = res
console.log(this.test)
});
}
这样,您只有console.log
在获得新值时才调用this.test
推荐阅读
- abap - 使用 ANY 或 DATA 键入字段符号
- typescript - 当我有很多打字文件时,如何让 Visual Studio 代码自动导入等工作?
- python - IndexError:即使输入读取文件完美,列表索引也超出范围
- azure - 更改 Azure VM 上的 DNS 后缀
- generics - 要求泛型类型重载运算符和运算结果也重载运算符
- javascript - Angular2用javascript突出显示html字符串中的一些单词
- arm - ARM Cortex M7 何时真正需要 CLREX?
- c++ - 如何在 C++ 中对静态缓冲区执行字符串格式化?
- javascript - 如何在 https://put.io 主页上重现星夜/流星动画?
- c++ - 为什么 if (a == b || c) && (d != 0) {operation 1} 默认运行但 (a == e || f) && (d!= 0) {op2} 被忽略?