我正在学习Angular 6,我正在尝试做一些超级假人的事情。
我正在尝试以Angular复制此JS代码:
var x;
function go(){
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json =>{
x = json;
console.log(x)
} )
}
go();
,我可以成功地将返回的值分配给X变量并打印它。
但是,当我尝试在Angular中进行相同的操作时,我无法在外部属性的承诺中分配返回的值。(我尝试打印时会变得不确定(
这是我尝试将上述JS代码转换为Angular语法而没有运气的方式:
import { Component, AfterContentInit } from "@angular/core";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent implements AfterContentInit {
obj;
go() {
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json =>{
this.obj = json;
})
}
ngAfterContentInit() {
this.go();
console.log(this.obj) // undefined
}
}
它与this
关键字有关吗?"这个"是指go()
方法的问题吗?如果是这样,我该如何从承诺内指出班级的OBJ属性?我迷路了。
谢谢。
这里的问题是console.log
实际上将在this.go()
完成之前执行。
但是您的功能this.go()
工作正常,this.obj
实际上将被修改,但仅在fetch
完成并使用其数据response.json()
返回之后,这再次发生在console.log
之后。
要确保您的逻辑在fetch
完成后运行,您必须在Promise回调函数中编写逻辑,如下所示。
import { Component, AfterContentInit } from "@angular/core";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent implements AfterContentInit {
obj;
go() {
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json =>{
this.obj = json;
console.log(this.obj) // runs after `fetch` finishes and will log the modified value.
})
}
ngAfterContentInit() {
this.go();
console.log(this.obj) // this will run before `this.go()` you have to wait for it to finish.
// result is undefined
}
}
更好地理解诺言,我建议这篇文章