如何在angular中返回多个语句?



我正在创建登录页面,并希望通过单个函数一起调用/Login和/send-otp api。我已经创建了一个登录注册页面。

我的代码:

user-data.service。ts:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
providedIn: 'root'
})
export class UserdataService {
url= 'http://localhost:9197/register';
url2= 'http://localhost:9197/login';
url3= 'http://localhost:9197/send-otp';
constructor(private http:HttpClient) {}
saveRegistration(data:any){
return this.http.post(this.url, data);
}
loginDone(ldata:any){
return this.http.post(this.url2, ldata);
return this.http.post(this.url3, ldata);
}
}

如何调用乘法api ??

loginDone(ldata:any){
return this.http.post(this.url2, ldata);
return this.http.post(this.url3, ldata);
}

在你的代码中应用TypeScript别名定义:

这里以一种更简单的方式,你有一个带有别名结构的多重返回。

type multi={
x:PelotaAzul,
y:PelotaRugosa,
}
function multiple():multi{
let x:PelotaAzul=new PelotaAzul("jj",5);
let y:PelotaRugosa=new PelotaRugosa("s",3,6)
let ab : multi ={x,y};
return ab;
}

你也可以像这样返回一个包含两个参数的数组

loginDone(ldata:any){
return [this.http.post(this.url2, ldata),this.http.post(this.url3, ldata)];
}

我发现创建别名更优雅,但为了更快的结果,请执行第二个。

你可能错过了思考你的问题。

首先。return语句总是会停止函数的执行,不管它后面是不是有100行。

其次,您的逻辑可能是:首先调用login,然后(使用或不使用响应)调用send-otp

或者,您的逻辑可能是:同时调用loginsend-otp,但是loginDone方法应该只在两个请求都运行良好的情况下返回一些有效状态。

这就是为什么其他答案是完全错误的。

你必须使用pipe和switchmap来级联你的观察对象,例如:

return of([this.url2, this.url3]).pipe(
switchMap((url) => this.http.post(url, ldata))
)

如果要返回多个值,可以这样返回。

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
providedIn: 'root'
})
export class UserdataService {
url= 'http://localhost:9197/register';
url2= 'http://localhost:9197/login';
url3= 'http://localhost:9197/send-otp';
constructor(private http:HttpClient) {}
saveRegistration(data:any){
return this.http.post(this.url, data);
}
loginDone(ldata:any){
return {url1: this.url, url2: this.url2, url3: this.url3};
}
}

如果你想调用多个api,选中这个。

https://medium.com/bb-tutorials-and-thoughts/how-to-make-parallel-api-calls-in-angular-applications-4b99227e7458

最新更新