如何使用 Async 和 await 从一个组件获取数据到另一个组件
How to get data from one component to another using Async and await
我有 2 个组件和 1 个服务文件
**组件**是我需要响应的地方
我正在尝试从组件 1 调用主组件中存在的函数,并且我正在从服务返回主组件的响应。
我很担心如何通过使用 Async 和 await 将相同的 API 响应从主组件传输到组件 1...请帮助我...:[=13=]
组件.ts
async data( ){
const same= await this.Mastercomponent.function();
console.log(same, ": function result");
Mastercomponent.ts
async function( ) {
this.service._getdata(ob).subscribe(
data => {
console.log(data, "Response Recieved in Mastercomponent");
return data;
})}
Service.ts
return this.http.post(param, { headers: head, responseType: 'text' }).pipe(
tap(data => {
console.log(data, "Response Recieved in Service");
}),
catchError(this.getError)
);
async
函数 return 承诺,但是您的主组件函数没有任何明确的 return
声明,因此它承诺 undefined
。唯一的 return
发生在与 async
函数的 return 值无关的回调中。
有多种解决方案可以使此功能正常工作,所以这只是其中之一:
function( ) {
return this.service._getdata(ob).toPromise().then(data => {
// ^^^^^^ ^^^^^^^^^^^^^^^^
console.log(data, "Response Recieved in Mastercomponent");
return data;
});
}
请注意,实际上您在这里不需要 async
关键字,因为现在您已经 return 一个承诺,并且不要使用 await
。作为一般规则,没有 await
的函数不需要 async
关键字(尽管如果包含它不会破坏代码)。
我有 2 个组件和 1 个服务文件 **组件**是我需要响应的地方 我正在尝试从组件 1 调用主组件中存在的函数,并且我正在从服务返回主组件的响应。
我很担心如何通过使用 Async 和 await 将相同的 API 响应从主组件传输到组件 1...请帮助我...:[=13=]
组件.ts
async data( ){
const same= await this.Mastercomponent.function();
console.log(same, ": function result");
Mastercomponent.ts
async function( ) {
this.service._getdata(ob).subscribe(
data => {
console.log(data, "Response Recieved in Mastercomponent");
return data;
})}
Service.ts
return this.http.post(param, { headers: head, responseType: 'text' }).pipe(
tap(data => {
console.log(data, "Response Recieved in Service");
}),
catchError(this.getError)
);
async
函数 return 承诺,但是您的主组件函数没有任何明确的 return
声明,因此它承诺 undefined
。唯一的 return
发生在与 async
函数的 return 值无关的回调中。
有多种解决方案可以使此功能正常工作,所以这只是其中之一:
function( ) {
return this.service._getdata(ob).toPromise().then(data => {
// ^^^^^^ ^^^^^^^^^^^^^^^^
console.log(data, "Response Recieved in Mastercomponent");
return data;
});
}
请注意,实际上您在这里不需要 async
关键字,因为现在您已经 return 一个承诺,并且不要使用 await
。作为一般规则,没有 await
的函数不需要 async
关键字(尽管如果包含它不会破坏代码)。