我有这个代码片段,我想将res(将整个json记录)分配给json变量,但是我无法做到这一点,因为记录json变量将返回一个未定义的对象
export class AppComponent {
title = 'app2';
json ;
constructor(private jsl : JsonLoadService)
{
this.json = this.jsl.getUrl().subscribe(res => {
console.log(res);
});
}
}
答案 0 :(得分:1)
您应该在订阅中执行以下操作
this.jsl.getUrl().subscribe(res => {
this.json = res;
console.log(this.json); // component variable now defined.
})
请记住,由于订阅的异步性质,this.json
仅在订阅运行后才定义。这个例子应该有助于形象化。
public ngOnInit(): void
{
this.jsl.getUrl().subscribe(res => {
this.json = res;
this.logData(); // will log your result
});
this.logData(); // will not log and will error
}
public logData(): void
{
console.log(this.json);
}