I am not following a tutorial, although I got the bare structure for the authentication logic from a post I found online and used that as a blueprint.
I actually had my code similar to your example, but I decided to handle everything in the authentication service because I want the user to login upon registration and I have no control over the back-end to add the logic there. So instead of repeating the logic for login twice I implemented all the login logic in one method in the auth service and then call that method whenever I need it (login and register).
So for example this is my login method in auth service:
async login(username, password) {
const loading = await this.loadingController.create({
duration: 5000,
message: "Please wait..."
});
loading.present();
return this.http
.post(apiEndPoint + "/jwt-auth/v1/token", {
username,
password
})
.subscribe(
res => {
console.log(res);
loading.dismiss();
this.storage
.set(TOKEN_KEY, res["token"])
.then(() => this.authenticationState.next(true));
},
ex => {
loading.dismiss();
console.log(ex);
this.errorMessage.next("Invalid username or password.");
}
);
}
Then I call it in the login.ts
onSubmit(form) {
this.authService.login(form.value.username, form.value.password);
}
And also in my register function in my user service (because I want the user to login upon registration):
register(user) {
console.log(user);
this.http
.post(apiEndPoint + "/wp/v2/users/register", {
username: user.username,
email: user.email,
password: user.password
})
.subscribe(
res => {
console.log(res);
this.authService.login(user.username, user.password);
},
ex => console.log(ex)
);
}
This was the only way I could think of for not repeating myself twice with the login logic.
And yes, I should probably avoid mixing async and await with Observables, I’ll see what I can do, I reckon it seem a bit messy (although it works).
I am not going to lie, it bothers a me a bit that the Angular team went with Observables for http requests, why not just use Promises like everyone else