Я пытаюсь получить объект учетной записи (в json) из моей базы данных через API (который я написал сам, он работает).Метод в сервисе для взаимодействия с API работает.Вот код для службы API взаимодействия:
import { Injectable } from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {Account} from './classes/account';
import {Observable} from 'rxjs';
@Injectable({
providedIn: 'root'
})
/* get from database:
Address: "awdawda"
CheckedInCamping: 0
CheckedInEvent: 0
DateOfBirth: "2000"
Email: "test@c.com"
Gender: "male"
Name: "firstname"
Password: "123456"
Phone: "+3161234567"
RFID: null
TicketId: 2
*/
export class ApiInteractionService {
private URLgeneral: string = 'http://local.propapi.com/api/';
constructor(private http: HttpClient) {
}
public getAccount(email: string, password: string): any { //Observable<Account>
this.http.get<Account[]>(this.URLgeneral + 'account/' + email + '/' + password).subscribe(a => {
if (a[0] == null){
console.log('(getAccount() - api service) got no data');
return null;
}
else {
console.log('(getAccount() - api service) data found:');
console.log(a[0]);
return a[0]; //returning the observable
}
});
}
public postAccount(a: Account){
console.log('(getAccount() - api service) before api post');
return this.http.post(this.URLgeneral, a);
}
}
Этот метод работает без проблем.Возможно, это не лучший способ сделать это, но это нормально.Авторизация не важна, как и безопасность.(школьный проект)
Я использую метод getAccount в loginService:
import {Injectable} from '@angular/core';
import {Account} from './classes/account';
import {ApiInteractionService} from './api-interaction.service';
@Injectable({
providedIn: 'root'
})
export class LoginService {
constructor(private api: ApiInteractionService) {
}
public logIn(email, password){
this.api.getAccount(email, password).subscribe(a => {
if (a == undefined){ //no account found
console.log('(logIn() - loginService) passed account was null');
return a; //should be null
}
else { //account found. setting sessionstorage and reloading the page
sessionStorage.setItem('account', JSON.stringify(a)); //set session variable
window.alert('Logged in as ' + a.name + '.');
location.replace('/landing');
return a;
}
});
}
public logOut(): void{
sessionStorage.removeItem('account'); //remove session variable with key 'account'
window.alert('Logged out.');
location.reload();
}
}
Этот метод вызывается из component.ts с данными из формы:
login.component.ts:
import {Component, OnInit} from '@angular/core';
import {LoginService} from '../login.service';
import {Account} from '../classes/account';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
email: string = 'test@c.com';
password: string = '123456';
// email: string;
// password: string;
constructor(private LoginService: LoginService) { }
ngOnInit() {
}
logIn(){
return this.LoginService.logIn(this.email, this.password);
}
}
login.component.html:
<div id="login" class="container-fluid text-center pt-5 text-light"> <!--main container-->
<div id="loginitems" class="w-25 flex-wrap flex-column rounded mx-auto p-3"> <!--div containing the items-->
<h1 class="mb-5">Log in</h1> <!--title-->
<!--region login form-->
<div class="d-flex py-2 px-3 w-100 mx-auto">
<span class="flex-column d-flex w-100">
<label class="my-2 form-row w-100">Email: <input class="ml-auto rounded border-0 bg-dark text-light p-1" type="email" (keydown.enter)="logIn()" [(ngModel)]="email" name="email"> </label> <!--email input-->
<label class="my-2 form-row mb-5 w-100">Password: <input class="ml-auto rounded border-0 bg-dark text-light p-1" type="password" (keydown.enter)="logIn()" [(ngModel)]="password" name="password"></label> <!--password input-->
<button class="flex-row mx-auto w-50 mt-5 btn-dark border-0 text-light py-2 rounded" (click)="logIn()">Log in</button> <!--log in button-->
</span>
</div>
<!--endregion-->
<!--region registration shortcut-->
<div class="mt-4">
<label>Don't have an account yet? Register <a routerLink="/register">here</a>!</label>
</div>
<!--endregion-->
</div>
при попытке нажать кнопку для входа в систему с данными (это на 100% уверенно вdb) выдает ошибку в веб-консоли, но после ошибки я регистрирую полученную учетную запись, которая является правильными данными:
ERROR TypeError: "this.api.getAccount(...) is undefined"
logIn http://localhost:4200/main.js:1093:9
logIn http://localhost:4200/main.js:1180:16
View_LoginComponent_0 ng:///AppModule/LoginComponent.ngfactory.js:109:23
handleEvent http://localhost:4200/vendor.js:43355:41
callWithDebugContext http://localhost:4200/vendor.js:44448:22
debugHandleEvent http://localhost:4200/vendor.js:44151:12
dispatchEvent http://localhost:4200/vendor.js:40814:16
renderEventHandlerClosure http://localhost:4200/vendor.js:41258:38
decoratePreventDefault http://localhost:4200/vendor.js:59150:36
invokeTask http://localhost:4200/polyfills.js:2743:17
onInvokeTask http://localhost:4200/vendor.js:36915:24
invokeTask http://localhost:4200/polyfills.js:2742:17
runTask http://localhost:4200/polyfills.js:2510:28
invokeTask http://localhost:4200/polyfills.js:2818:24
invokeTask http://localhost:4200/polyfills.js:3862:9
globalZoneAwareCallback http://localhost:4200/polyfills.js:3888:17
LoginComponent.html:13:16
ERROR CONTEXT
Object { view: {…}, nodeIndex: 22, nodeDef: {…}, elDef: {…}, elView: {…} }
LoginComponent.html:13:16
(getAccount() - api service) data found: api-interaction.service.ts:35:16
{…}
Address: "awdawda"
CheckedInCamping: 0
CheckedInEvent: 0
DateOfBirth: "2000"
Email: "test@c.com"
Gender: "male"
Name: "firstname"
Password: "123456"
Phone: "+3161234567"
RFID: null
TicketId: 2
<prototype>: Object { … }
Почему я получаю эту ошибку?