英文:
Type 'Promise<any>' is not assignable to type 'string'
问题
我正在使用 async 和 promise 如下所示,我想等待 img
值返回。
ngOnInit(): void {
...
...
this.auth.msg.subscribe((res) => {
let img = this.fetchImage(this.user.id);
this.url = img; // 获取错误
...
});
}
async fetchImage(Id) {
let result: any;
let payload = {
Id: Id
};
result = await this.Sev.getPicture(payload).toPromise();
return result.response;
}
当我将 img
响应传递给其他变量时出现此错误:
类型 'Promise
' 不能赋值给类型 'string'
英文:
I'm using async and promise like given below, I want to wait for the img
value to be returned.
ngOnInit(): void {
...
...
this.auth.msg.subscribe((res) => {
let img=this.fetchImage(this.user.id);
this.url=img; // getting error
...
});
}
async fetchImage(Id) {
let result: any;
let payload = {
Id: Id
};
result = await this.Sev.getPicture(payload).toPromise();
return result.response;
}
When I pass img
response to some other variable getting this error:
> Type 'Promise<any>' is not assignable to type 'string'
答案1
得分: 2
The error message mentions that your fetchImage
returns a Promise.
To get the value from the Promise, either:
- 使用回调函数
this.auth.msg.subscribe((res: any) => {
this.fetchImage(this.user.id)
.then((value) => {
this.url = img;
});
});
- 使用 async/await
this.auth.msg.subscribe(async (res: any) => {
let img = await this.fetchImage(this.user.id);
this.url = img;
});
.toPromise()
已经在 RxJS 7 中弃用。建议根据RxJS文档中所述,将 .toPromise()
迁移到 firstValueFrom
/lastValueFrom
:
import { lastValueFrom } from 'rxjs';
async fetchImage(Id)
{
let result: any;
let payload = {
Id: Id
};
result = await lastValueFrom(this.Sev.getPicture(payload));
return result.response;
}
英文:
The error message mentions that your fetchImage
returns a Promise.
To get the value from the Promise, either:
- A callback function
this.auth.msg.subscribe((res: any) => {
this.fetchImage(this.user.id)
.then((value) => {
this.url = img;
});
});
- Use async/await
this.auth.msg.subscribe(async (res: any) => {
let img = await this.fetchImage(this.user.id);
this.url = img;
});
While .toPromise()
is deprecated from RxJS 7. Recommend migrating the .toPromise()
with firstValueFrom
/lastValueFrom
as stated in the RxJS documentation:
import { lastValueFrom } from 'rxjs';
async fetchImage(Id)
{
let result: any;
let payload = {
Id: Id
};
result = await lastValueFrom(this.Sev.getPicture(payload));
return result.response;
}
答案2
得分: 1
你可以尝试使用 switchMap。
this.auth.msg.pipe(
switchMap(_ => this.fetchImage(this.user.id))
).subscribe((img) => {
this.url = img;
...
});
英文:
You could try switchMap
this.auth.msg.pipe(
switchMap(_ => this.fetchImage(this.user.id))
).subscribe((img) => {
this.url=img;
...
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论