我正在写Angular6 (打字本)。我想用下面的代码把承诺联系起来.
public start() {
this.p1()
.then(this.p2)
.then(this.p3)
.catch((err) => console.log(err));
}
public p1(): Promise<string> {
return new Promise((resolve, reject) => {
this.httpService.sendHello().subscribe(response => {
resolve();
});
});
}
public p2(): Promise<string> {
return new Promise((resolve, reject) => {
this.httpService.sendHello().subscribe(response => {
resolve();
});
});
}
public p3(): Promise<string> {
return new Promise((resolve, reject) => {
this.httpService.sendHello().subscribe(response => {
resolve();
});
});
}
但出现“无法读取未定义的属性'httpService‘”时出现错误。
如何在承诺链中共享angular6服务?
谢谢你的帮助,
发布于 2019-05-24 01:09:58
当不使用箭头函数时,类型记录不绑定this
。
而不是then(this.p2)
,您可以编写then(() => this.p2())
public start() {
this.p1()
.then(() => this.p2())
.then(() => this.p3())
.catch((err) => console.log(err));
}
public p1(): Promise<string> {
return new Promise((resolve, reject) => {
this.httpService.sendHello().subscribe(response => {
resolve();
});
});
}
public p2(): Promise<string> {
return new Promise((resolve, reject) => {
this.httpService.sendHello().subscribe(response => {
resolve();
});
});
}
public p3(): Promise<string> {
return new Promise((resolve, reject) => {
this.httpService.sendHello().subscribe(response => {
resolve();
});
});
}
发布于 2019-05-24 01:06:15
将它作为函数的参数,如下所示:
public start() {
this.p1(this.httpService)
.then(this.p2)
.then(this.p3)
.catch((err) => console.log(err));
}
public p1(httpService: HttpService): Promise<string> {
return new Promise((resolve, reject) => {
httpService.sendHello().subscribe(response => {
resolve();
});
});
}
发布于 2019-05-24 01:08:38
这是this
上下文。将它们转换为箭头函数:
public p1 = (): Promise<string> => { //...
https://stackoverflow.com/questions/56289254
复制