Angular http
hej po api zwracane
mam takie cos w json { "id": 2, "login": "emil",
"password":
"$2a$11$vy4LqCkiTF8H8.gqmjJUQ.7E/wSZrJXRnjZbi8jpSkIA4iAcvKSFe",
"dataUtworzenia": "2025-05-08", "imie":
"Emil", "nazwisko": "Jan" } zmapuj mi to na model
w angularze
Oto jak możesz zmapować tę odpowiedź JSON na model w
Angularze:
1. Najpierw stwórz
interfejs TypeScript reprezentujący model:
typescript
Copy
Download
export interface User {
id: number;
login: string;
password: string;
dataUtworzenia: string;
imie: string;
nazwisko: string;
}
2. Jeśli chcesz użyć
klasy zamiast interfejsu (np. żeby dodać metody):
typescript
Copy
Download
export class User {
constructor(
public id: number,
public login: string,
public password: string,
public dataUtworzenia: string,
public imie: string,
public nazwisko: string
) {}
}
3. W komponencie lub
serwisie, gdzie pobierasz dane, możesz je mapować:
typescript
Copy
Download
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { User } from './user.model';
@Injectable({
providedIn: 'root'
})
export class UserService {
constructor(private http: HttpClient) {}
getUser(): Observable<User> {
return this.http.get<User>('twoje_api_endpoint');
// Jeśli potrzebujesz dodatkowego
mapowania:
// .pipe(map(response => new
User(response.id, response.login, ...)));
}
}
4. Jeśli chcesz parsować
datę na obiekt Date, możesz zmodyfikować interfejs/klasę:
typescript
Copy
Download
export interface User {
id: number;
login: string;
password: string;
dataUtworzenia: Date;
imie: string;
nazwisko: string;
}
// W serwisie:
getUser(): Observable<User> {
return this.http.get<any>('twoje_api_endpoint').pipe(
map(response => ({
...response,
dataUtworzenia: new Date(response.dataUtworzenia)
}))
);
}
5. W komponencie możesz
użyć tego w ten sposób:
typescript
Copy
Download
import { Component, OnInit } from '@angular/core';
import { UserService } from './user.service';
import { User } from './user.model';
@Component({
selector: 'app-user',
templateUrl: './user.component.html'
})
export class UserComponent implements OnInit {
user: User;
constructor(private userService: UserService) {}
ngOnInit() {
this.userService.getUser().subscribe(user => {
this.user = user;
});
}
}
W szablonie HTML możesz potem wyświetlać dane
użytkownika używając np. {{user?.imie}} {{user?.nazwisko}}.
ok to zrob do konca
najpierw zrob serwis ktory zaloguje z endpointu api dotneta takiego
[HttpPost("zaloguj")] public IActionResult
zalogujUzytkownika([FromBody]UzytkownikZalogujDTO uzytkownikZalogujDTO) {
AppDbContext baza = new AppDbContext(); Uzytkownik znaleziony =
baza.Uzytkownicy.FirstOrDefault(p => p.login == uzytkownikZalogujDTO.login);
if (znaleziony != null) { if
(BCrypt.Net.BCrypt.Verify(uzytkownikZalogujDTO.password, znaleziony.password))
{ return Ok(znaleziony); } else { return BadRequest("Błedne hasło/brak
użytkownika"); } } else { return BadRequest("Błędne hasło/brak
użytkownika"); } }
Oto kompletna implementacja serwisu w Angularze do
logowania użytkownika z endpointu .NET:
1. Najpierw zdefiniuj
modele TypeScript:
models/uzytkownik-zaloguj-dto.model.ts:
typescript
Copy
Download
export interface UzytkownikZalogujDTO {
login: string;
password: string;
}
models/uzytkownik.model.ts:
typescript
Copy
Download
export interface Uzytkownik {
id: number;
login: string;
password: string; // Hasło zahashowane
dataUtworzenia: string;
imie: string;
nazwisko: string;
}
2. Stwórz serwis do
logowania:
services/auth.service.ts:
typescript
Copy
Download
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, tap } from 'rxjs';
import { UzytkownikZalogujDTO } from '../models/uzytkownik-zaloguj-dto.model';
import { Uzytkownik } from '../models/uzytkownik.model';
@Injectable({
providedIn: 'root'
})
export class AuthService {
private apiUrl = 'https://twoj-api.example.com/api/uzytkownik'; // Zmień na swój endpoint
constructor(private http: HttpClient) { }
zaloguj(uzytkownikZalogujDTO: UzytkownikZalogujDTO): Observable<Uzytkownik> {
return this.http.post<Uzytkownik>(`${this.apiUrl}/zaloguj`, uzytkownikZalogujDTO)
.pipe(
tap(uzytkownik => {
// Tutaj możesz zapisać użytkownika w localStorage lub
serwisie stanu
localStorage.setItem('currentUser', JSON.stringify(uzytkownik));
})
);
}
wyloguj(): void {
localStorage.removeItem('currentUser');
}
getZalogowanyUzytkownik(): Uzytkownik | null {
const user = localStorage.getItem('currentUser');
return user ? JSON.parse(user) : null;
}
czyZalogowany(): boolean {
return this.getZalogowanyUzytkownik() !== null;
}
}
3. Stwórz komponent do
logowania:
components/login/login.component.ts:
typescript
Copy
Download
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { UzytkownikZalogujDTO } from '../../models/uzytkownik-zaloguj-dto.model';
import { AuthService } from '../../services/auth.service';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent {
uzytkownik: UzytkownikZalogujDTO = {
login: '',
password: ''
};
blad = '';
constructor(private authService: AuthService, private router: Router) {}
zaloguj(): void {
this.authService.zaloguj(this.uzytkownik).subscribe({
next: () => {
this.router.navigate(['/dashboard']); // Przekieruj po zalogowaniu
},
error: (err) => {
this.blad = 'Błędny login lub hasło';
console.error('Błąd logowania:', err);
}
});
}
}
components/login/login.component.html:
html
Copy
Download
Run
<div class="login-container">
<h2>Logowanie</h2>
<form (ngSubmit)="zaloguj()">
<div class="form-group">
<label for="login">Login:</label>
<input type="text" id="login" [(ngModel)]="uzytkownik.login" name="login" required>
</div>
<div class="form-group">
<label for="password">Hasło:</label>
<input type="password" id="password" [(ngModel)]="uzytkownik.password" name="password" required>
</div>
<button type="submit">Zaloguj</button>
<div *ngIf="blad" class="error-message">{{blad}}</div>
</form>
</div>
4. Dodaj
HttpInterceptor do obsługi błędów (opcjonalne):
interceptors/error.interceptor.ts:
typescript
Copy
Download
import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor,
HttpErrorResponse
} from '@angular/common/http';
import { Observable, catchError, throwError } from 'rxjs';
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
return next.handle(request).pipe(
catchError((error: HttpErrorResponse) => {
if (error.status === 400 || error.status === 401) {
// Obsługa błędów logowania
console.error('Błąd autentykacji:', error.error);
}
return throwError(() => error);
})
);
}
}
5. Zarejestruj
interceptor w module głównym:
app.module.ts:
typescript
Copy
Download
import { NgModule } from '@angular/core';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { ErrorInterceptor } from './interceptors/error.interceptor';
@NgModule({
imports: [HttpClientModule],
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true }
]
})
export class AppModule { }
6. Dodaj guard do
ochrony tras (opcjonalne):
guards/auth.guard.ts:
typescript
Copy
Download
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { AuthService } from '../services/auth.service';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(): boolean {
if (this.authService.czyZalogowany()) {
return true;
} else {
this.router.navigate(['/login']);
return false;
}
}
}
Teraz możesz użyć tego
w routingu:
typescript
Copy
Download
const routes: Routes = [
{ path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] },
{ path: 'login', component: LoginComponent }
];
Ta implementacja:
1. Wysyła dane logowania
do endpointu .NET
2. Obsługuje odpowiedź
(sukces/niepowodzenie)
3. Przechowuje
zalogowanego użytkownika w localStorage
4. Udostępnia metody do
sprawdzania stanu logowania
5. Chroni trasy przed
nieautoryzowanym dostępem
Pamiętaj, aby dostosować endpointy (apiUrl) do swojej
konfiguracji backendu.
Komentarze
Prześlij komentarz