如何将我的 angular-nativescript 应用程序连接到数据库进行登录?



我正在尝试通过NativeScript和Angular创建一个应用程序,该应用程序将管理公司员工的工作时间。

所以,我必须设置一个登录页面,这是我的问题:我在点击 LOGIN 按钮时链接了一个功能,单击它后,我将用户名和密码发送到我尝试连接的服务和端点 (mypath/api/auth.php(。

在这个php文件中,我设置了数据库连接和一个SELECT查询,该查询以$_POST函数的形式接收用户名和密码。但是,现在,当我点击我的登录按钮时,即使凭据是对还是错,我也会收到[Object Object]警报。

我是NativeScript和Angular的初学者。

我的PHP用户验证功能:

$username = $_POST["username"];
$password = $_POST["password"];
$conn = getDB();
$hash_pwd = hash('sha256', $password);
$stmt = $conn->prepare("SELECT * FROM dipendenti WHERE cod_fiscale=:username AND password=:password");
$stmt->bindParam("username", $username,PDO::PARAM_STR) ;
$stmt->bindParam("password", $hash_pwd,PDO::PARAM_STR) ;
$stmt->execute();
$count=$stmt->rowCount();
$data=$stmt->fetch(PDO::FETCH_OBJ);
closeDB($conn);
return json_encode($data);

我的用户服务文件:

import { Injectable } from "@angular/core";
import { HttpClient, HttpHeaders, HttpResponse } from "@angular/common/http";
import { Observable, throwError } from "rxjs";
import { catchError, map, tap } from "rxjs/operators";
import { Auth } from "./auth.model";
import { Config } from "../config";
@Injectable()
export class AuthService {
constructor(private http: HttpClient) { }
login( user: Auth) {
if(!user.codFiscale || !user.password) {
return throwError("Devi inserire sia codice fiscale sia la tua password per accedere");
}
return this.http.post(Config.apiUrl + 'api/auth.php', 
JSON.stringify({
username: user.codFiscale,
password: user.password
}),
{ 
headers: this.getCommonHeaders()
}).pipe(
map(response => response),
catchError(this.handleErrors)
);
}
getCommonHeaders() {
return {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*"
}
}
handleErrors(error: Response) {
console.log(JSON.stringify(error));
return throwError(error);
}
}

我的函数在点击按钮时触发:

submitLogin() {
if(this.isLoggingIn) {
this.authService.login(this.user).subscribe(
() => {
this.router.navigate(["/home"]);
},
(exception) => {
if(exception.error && exception.error.description) {
alert(exception.error.description);
} else {
alert(exception.error);
}
}
);
}
}

我忘记了什么吗?

我在 nativescript-vue 中这样做,也许你需要调整角度。 我为此使用 axios 插件,它也适用于 ns-angular,我只是不知道如何在角度上配置它......但代码是这样的:

async submitLogin() {
const data = {
email: this.user.email,
password: this.user.password
};
try {
const res = (await api.post(this.getApiUrl+"/app/services/login.php", data)).data;
if (res.code === 200){
//handle login success
}
else if (res.code === 500){
//handle login fail
}
}
catch (e) {
console.error("Connection error: ", e);
}
},

其中 api.post 是:

post(url, request, config) {
return axios.post(url, request, config)
.then((response) => Promise.resolve(response))
.catch((error) => Promise.reject(error));
},

编辑:res.code 是我在响应中发送的自定义响应,它不是默认的!

最新更新