我需要将HTML表单中提供的电子邮件地址与我从模拟API获得的电子邮件地址进行比较。如果电子邮件地址匹配,则足以进行成功的授权。我试图通过在isAuthorized
方法中创建布尔变量loginUser()
来对此进行归档,将其初始值设置为false
,如果电子邮件地址匹配,我就试图在http请求的订阅中将其设置为true
,但这不起作用。
如何执行上述授权?我是Angular的新手。
login.component.ts
import { Component, OnInit, HostListener } from '@angular/core';
import { Router } from '@angular/router';
import { LoginStateService } from 'src/app/login-state.service'
import { UserService } from '../user.service';
import { HttpService } from '../http.service';
interface Users {
[key: string]: {
email?: string;
}
}
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css'],
})
export class LoginComponent implements OnInit {
loginStateText: string;
loginRout: string;
constructor(
private router: Router,
private user: UserService,
private loginState: LoginStateService,
private cssHelper: CssHelperService,
private http: HttpService) {
}
ngOnInit() {
this.loginState.currentButtonText.subscribe(
loginStateText => this.loginStateText = loginStateText
);
this.loginState.currentRout.subscribe(
loginRout => this.loginRout = loginRout
);
}
loginUser(e){
e.preventDefault;
let email: string = e.target.elements[0].value;
let isAuthorized: boolean = false;
this.http.getUserId().subscribe(data => {
alert('Input: ' + email + ' / JSON: ' + data[0].email);
if(email == data[0].email){
console.log('Auth OK');
isAuthorized = true;
}
else{
console.log('Auth not OK');
}
})
if(isAuthorized){
this.user.setUserLoggedIn();
this.loginState.ChangeLoginButtonText("Logout");
this.loginState.ChangeLoginRout('/logout');
alert("Authorization success");
this.router.navigate(["/dashboard"]);
}else{
alert('Authorization failed, please check your credentials.')
}
}
}
答案 0 :(得分:0)
您的逻辑应在从服务器获取数据后执行。现在,代码已编写完毕,无需等待api请求完成。
只需移动
if(isAuthorized){
this.user.setUserLoggedIn();
this.loginState.ChangeLoginButtonText("Logout");
this.loginState.ChangeLoginRout('/logout');
alert("Authorization success");
this.router.navigate(["/dashboard"]);
}else{
alert('Authorization failed, please check your credentials.')
}
进入订阅回调。
loginUser(e){
e.preventDefault;
let email: string = e.target.elements[0].value;
let isAuthorized: boolean = false;
this.http.getUserId().subscribe(data => {
alert('Input: ' + email + ' / JSON: ' + data[0].email);
if(email == data[0].email){
console.log('Auth OK');
isAuthorized = true;
}
else{
console.log('Auth not OK');
}
if(isAuthorized){ // here your logic should execute
this.user.setUserLoggedIn();
this.loginState.ChangeLoginButtonText("Logout");
this.loginState.ChangeLoginRout('/logout');
alert("Authorization success");
this.router.navigate(["/dashboard"]);
}else{
alert('Authorization failed, please check your credentials.')
}
})
}