I am doing an authentication service, if it is correct it allows you to continue, but if not, you can get several messages, The problem is that I do not know how to take the service variables to the component so that I can show it in the view.
Service:
export class DataService {
public errorMessage: string;
public showAlert: boolean = false;
public checkCredentials(url:string, username:string, password:string):Observable<any>{
return this.http.get<Object>(url).pipe(tap (users => {
const checkCookie = this.cookie.get('login');
if (users.find(u => u.user === username)) {
this.usuario = users.find(u => u.user === username);
if (username === this.usuario.user && password === this.usuario.pass && !checkCookie) {
this.cookie.set('login', this.usuario.mail);
this.router.navigate(['configuration']);
} else {
this.errorMesssage = 'Se han introducido unas credenciales incorrectas';
this.showAlert = true;
}
} else {
this.errorMessage = 'El usuario introducido no se ha encontrado';
this.showAlert = true;
}
return this.errorMesssage;
}));
1º Here I have to send the Message and the boolean and I only have a return.
2nd Also gives error else {
this.errorMesssage = 'Se han introducido unas credenciales incorrectas';
The error is:
La propiedad "errorMesssage" no existe en el tipo "DataService". ¿Quería decir "errorMessage"?
3º How to receive service returns in the component.
const url = 'assets/users.json';
this.service.checkCredentials(url,this.username,this.password).subscribe();
Edited - >
Service:
public checkCredentials(url:string, username:string, password:string):Observable<any>{
return this.http.get<Object>(url).pipe(tap (users => {
const checkCookie = this.cookie.get('login');
let messageError = { message:"", showAlert:false };
if (users.find(u => u.user === username)) {
this.usuario = users.find(u => u.user === username);
if (username === this.usuario.user && password === this.usuario.pass && !checkCookie) {
this.cookie.set('login', this.usuario.mail);
this.router.navigate(['configuration']);
} else {
messageError.message = "Se han introducido unas credenciales incorrectas";
messageError.showAlert= true;
}
} else {
messageError.message = "El usuario introducido no se ha encontrado";
messageError.showAlert= true;
}
return messageError;
}));
}
Component
public checkCredentials = function () {
const url = 'assets/users.json';
this.service.checkCredentials(url, this.username, this.password).subscribe(result => {
console.log('result', result); //Devuelve a los usuarios
this.errorMessage = result.message;
this.showAlert = result.showAlert;
});
}
If instead of using tap use map, an error in the find or that or all the code is put in red