Hello I'm having a nesting subscription in my angular and i'm handling in the below way and heard it's a bad approach.
Can anyone let me know the best possible way to do? It will really help me to learn.Below is my code, please have a look. TIA
login.ts
login(email: string, password: string) {
const user = new FormData();
user.append("username", email);
user.append("password", password);
this.http
.post<any>("api1", user)
.subscribe((response) => {
this.myToken = response.access_token;
console.log(this.myToken);
if (this.myToken) {
const body = new HttpParams()
.set("username", email)
.set("password", password);
return this.http
.post<any>("api2", body, {
headers: new HttpHeaders({
"Content-Type": "application/x-www-form-urlencoded",
Authorization: `${this.myToken}`,
})
})
.subscribe((response) => console.log(response));
} else {
alert("error: Not authorized");
}
});
}
2)When my component is loaded i need to check my get api response. If I get get API
response == null
I need to post data using the same form. When my get API response != null
, then I need to patch the values to the form and should able to update it using PUT API
form.ts
getVal() {
http.get<any>(API).subscribe(response => {
this.getResponse= response;
if (this.getResponse != null) {
this.form.patchValue({. //append the values to the form
username: response.username,
})
})
}
onRegisterSubmit(form) {
this.username = form.value
console.log(form.value);
if (this.getResponse != null) {
//I want to enable update button and update api here
http.put<any>(api, this.username).subscribe(resposne =>
console.log(response) )
} if(response == null) {
http.post<any>(api, this.username).subscribe(resposne =>
console.log(response) )
//I want to send data using post method.
}
}