我正在研究Angular6(打字稿)。我正在尝试用以下代码链接promise ...
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'”。
我应该如何在promise链中共享angular6服务?
感谢您的帮助,
答案 0 :(得分:1)
您将其作为函数的参数,例如:
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();
});
});
}
答案 1 :(得分:1)
这是this
上下文。将它们转换为箭头函数:
public p1 = (): Promise<string> => { //...
答案 2 :(得分:1)
当您不使用箭头功能时,Typescript不会绑定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();
});
});
}
答案 3 :(得分:1)
您可以使用RxJS
forkjoin
,这里是示例
ngOnInit() {
chainCall().subscribe(resp=> {
console.log(resp);
})
}
chainCall(): Observable<any[]> {
const response1 = this.httpService.sendHello();
const response2 = this.httpService.sendHello();
return forkJoin([response1, response2]);
}