> For the complete documentation index, see [llms.txt](https://odilbeks-organization.gitbook.io/angular-ustoz-shogirt/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://odilbeks-organization.gitbook.io/angular-ustoz-shogirt/http-va-backend-integration.md).

# HTTP va Backend Integration

#### Mundarija

1. HTTP va API nima?
2. HttpClient
3. RESTfull API’lar
   1. GET
   2. POST
   3. PUT
   4. DELETE
4. Observable nima?
5. Error handling
6. Query Parameters va Headers

***

### 1. HTTP va API nima?

**HTTP** - bu brauzer va server o'rtasida ma'lumot almashish protokoli.

**API (Application Programming Interface)** - bu backend server bilan ishlash uchun interface.

**RESTful API** - bu ma'lumotlar bilan ishlashning standart usuli:

* `GET` - ma'lumot olish
* `POST` - yangi ma'lumot yaratish
* `PUT` - ma'lumotni yangilash
* `DELETE` - ma'lumotni o'chirish

**Misol:**

```
GET    /api/students     → Barcha talabalar
GET    /api/students/5   → 5-id li talaba
POST   /api/students     → Yangi talaba qo'shish
PUT    /api/students/5   → 5-id li talabani yangilash
DELETE /api/students/5   → 5-id li talabani o'chirish

```

***

### 2. HttpClient sozlash

{% hint style="info" %}
Angularda HTTP orqali biror APIga so’rov qilish uchun `HttpClient` service’i kerakli service yoki componentda inject qilinadi va kerakli so’rov chaqiriladi. Buning uchun esa `provideHttpClient` ni app.configda import qilish kerak bo’ladi!
{% endhint %}

#### `provideHttpClient` ni import qilish

```tsx
// **app.config.ts**
import { ApplicationConfig } from '@angular/core';
import { provideHttpClient } from '@angular/common/http';

export const appConfig: ApplicationConfig = {
  providers: [
    provideHttpClient()
  ]
};
```

**Muhim:** `provideHttpClient` bir marta app.configda import qilinsa bo’lgani!

***

### 3. RESTfull API’lar

#### 3.1 GET so'rovi - Ma'lumot olish

**student.service.ts:**

```tsx
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

export interface Student {
  id: number;
  name: string;
  email: string;
  grade: number;
}

@Injectable({
  providedIn: 'root'
})
export class StudentService {
  private apiUrl = '<http://localhost:3000/api/students>';

  constructor(private http: HttpClient) { }

  // Barcha talabalarni olish
  getStudents(): Observable<Student[]> {
    return this.http.get<Student[]>(this.apiUrl);
  }

  // Bitta talabani olish
  getStudent(id: number): Observable<Student> {
    return this.http.get<Student>(`${this.apiUrl}/${id}`);
  }
}
```

**Komponentda ishlatish:**

```tsx
import { Component, OnInit } from '@angular/core';
import { StudentService, Student } from './services/student.service';

@Component({
  selector: 'app-students',
  templateUrl: './students.component.html'
})
export class StudentsComponent implements OnInit {
  students: Student[] = [];
  loading: boolean = false;
  error: string = '';

  constructor(private studentService: StudentService) { }

  ngOnInit() {
    this.loadStudents();
  }

  loadStudents() {
    this.loading = true;

    this.studentService.getStudents().subscribe({
      next: (data) => {
        this.students = data;
        this.loading = false;
      },
      error: (err) => {
        this.error = 'Ma\\'lumotlarni yuklashda xatolik!';
        this.loading = false;
        console.error('Error:', err);
      }
    });
  }
}

```

**Template:**

```html
<div class="students-container">
  <h2>Talabalar ro'yxati</h2>

  @if (loading) {
    <p>Yuklanmoqda...</p>
  }

  @if (error) {
    <div class="error">{{ error }}</div>
  }

  @if (!loading && !error) {
    <div class="students-list">
      @for (student of students; track student.id) {
        <div class="student-card">
          <h3>{{ student.name }}</h3>
          <p>Email: {{ student.email }}</p>
          <p>Sinf: {{ student.grade }}</p>
        </div>
      } @empty {
        <p>Talabalar topilmadi</p>
      }
    </div>
  }
</div>

```

{% hint style="info" %}
E’tibor bergan bo’lsangiz HttpClient service’ida `.get` nomli method GET so’rovlarni ishlarish uchun foydalanilmoqda!
{% endhint %}

***

#### 3.2 POST so'rovi - Ma'lumot yaratish

**Misol uchun Serverdagi talabalar ro’yxatiga yangi talaba qo'shmoqchimiz deylik.**

**Service da:**

```tsx
// student.service.ts
export class StudentService {
  // ...

  // Yangi talaba qo'shish
  createStudent(student: Student): Observable<Student> {
    return this.http.post<Student>(this.apiUrl, student);
  }
}
```

**Komponentda:**

```tsx
@Component({
  selector: 'app-student-form',
  templateUrl: './student-form.component.html'
})
export class StudentFormComponent {
  student: Student = {
    id: 0,
    name: '',
    email: '',
    grade: 1
  };

  constructor(private studentService: StudentService) { }

  onSubmit() {
    this.studentService.createStudent(this.student).subscribe({
      next: (newStudent) => {
        console.log('Talaba qo\\'shildi:', newStudent);
        alert('Talaba muvaffaqiyatli qo\\'shildi!');
        this.resetForm();
      },
      error: (err) => {
        console.error('Xatolik:', err);
        alert('Talaba qo\\'shishda xatolik!');
      }
    });
  }

  resetForm() {
    this.student = {
      id: 0,
      name: '',
      email: '',
      grade: 1
    };
  }
}
```

**Template:**

```html
<div class="student-form">
  <h2>Yangi talaba qo'shish</h2>

  <form (ngSubmit)="onSubmit()">
    <div class="form-group">
      <label>Ism:</label>
      <input type="text" [(ngModel)]="student.name" name="name" required>
    </div>

    <div class="form-group">
      <label>Email:</label>
      <input type="email" [(ngModel)]="student.email" name="email" required>
    </div>

    <div class="form-group">
      <label>Sinf:</label>
      <input type="number" [(ngModel)]="student.grade" name="grade" min="1" max="11" required>
    </div>

    <button type="submit">Qo'shish</button>
  </form>
</div>

```

***

#### 3.3 PUT so'rovi - Ma'lumotni yangilash

**Talaba ma'lumotlarini tahrirlash.**

**Service da:**

```tsx
// student.service.ts
export class StudentService {
  // ...

  // Talabani yangilash
  updateStudent(id: number, student: Student): Observable<Student> {
    return this.http.put<Student>(`${this.apiUrl}/${id}`, student);
  }
}

```

**Komponentda:**

```tsx
@Component({
  selector: 'app-student-edit',
  templateUrl: './student-edit.component.html'
})
export class StudentEditComponent implements OnInit {
  studentId: number = 0;
  student: Student = {
    id: 0,
    name: '',
    email: '',
    grade: 1
  };

  constructor(
    private route: ActivatedRoute,
    private studentService: StudentService,
    private router: Router
  ) { }

  ngOnInit() {
    // URL dan ID olish
    this.studentId = Number(this.route.snapshot.paramMap.get('id'));
    this.loadStudent();
  }

  loadStudent() {
    this.studentService.getStudent(this.studentId).subscribe({
      next: (data) => {
        this.student = data;
      },
      error: (err) => {
        console.error('Xatolik:', err);
      }
    });
  }

  onSubmit() {
    this.studentService.updateStudent(this.studentId, this.student).subscribe({
      next: (updatedStudent) => {
        console.log('Yangilandi:', updatedStudent);
        alert('Ma\\'lumotlar yangilandi!');
        this.router.navigate(['/students']);
      },
      error: (err) => {
        console.error('Xatolik:', err);
        alert('Yangilashda xatolik!');
      }
    });
  }
}

```

***

#### 3.4 DELETE so'rovi - Ma'lumotni o'chirish

**Talabani o'chirish**

**Service da:**

```tsx
// student.service.ts
export class StudentService {
  // ...

  // Talabani o'chirish
  deleteStudent(id: number): Observable<void> {
    return this.http.delete<void>(`${this.apiUrl}/${id}`);
  }
}

```

**Komponentda:**

```tsx
@Component({
  selector: 'app-students-list',
  templateUrl: './students-list.component.html'
})
export class StudentsListComponent {
  students: Student[] = [];

  constructor(private studentService: StudentService) { }

  deleteStudent(id: number) {
    if (confirm('Talabani o\\'chirmoqchimisiz?')) {
      this.studentService.deleteStudent(id).subscribe({
        next: () => {
          console.log('O\\'chirildi');
          // Ro'yxatni yangilash
          this.students = this.students.filter(s => s.id !== id);
          alert('Talaba o\\'chirildi!');
        },
        error: (err) => {
          console.error('Xatolik:', err);
          alert('O\\'chirishda xatolik!');
        }
      });
    }
  }
}

```

**Template:**

```html
<div class="students-list">
  @for (student of students; track student.id) {
    <div class="student-card">
      <h3>{{ student.name }}</h3>
      <p>{{ student.email }}</p>
      <button (click)="deleteStudent(student.id)" class="btn-delete">
        O'chirish
      </button>
    </div>
  }
</div>

```

***

## 4. Observable nima?

Dasturlashda ba’zi ma’lumotlar **darhol kelmaydi**.

Masalan:

* serverdan ma’lumot olish,
* tugma bosilishini kutish,
* foydalanuvchi biror amal bajarishini kutish.

Shunday holatlarda Angular **Observable** dan foydalanadi.

***

### Observable juda sodda qilib aytganda

**Observable — bu keyinroq keladigan ma’lumotni kutib turadigan narsa.**

Yana ham soddaroq qilib:

> Observable — “agar ma’lumot kelsa, menga ayt” degan mexanizm.

***

### Hayotiy misol

Tasavvur qiling, siz **Telegram kanalga obuna bo‘ldingiz**:

* Hozircha xabar yo‘q
* Bir ozdan keyin xabar keladi
* Keyin yana kelishi mumkin
* Qachon kelishini oldindan bilmaysiz

Siz xabarni **kutib o‘tirmaysiz**, balki o‘z ishingizni qilaverasiz.

Xabar kelganda esa — uni o‘qiysiz.

👉 Bu holat Observable’ga juda o‘xshaydi.

***

### Angular’da Observable qayerda ishlatiladi?

Angular’da Observable quyidagi holatlarda ishlatiladi:

* API’dan ma’lumot olishda
* Tugma bosilganda
* Forma qiymati o‘zgarganda
* Sahifa (route) almashganda

Bu holatlarning barchasida **ma’lumot qachon kelishi noma’lum**.

***

### Oddiy Angular misol

```tsx
this.http.get('/api/users')

```

Bu kod:

* hozircha hech qanday ma’lumot bermaydi
* server javob berganda ma’lumot beradi

Bu — **Observable**

***

### Nega obuna bo‘lish kerak?

Observable o‘zi-o‘zidan ishlamaydi.

Uni **kuzatish (obuna bo‘lish)** kerak.

Agar obuna bo‘lmasangiz:

```tsx
this.http.get('/api/users');

```

👉 Hech narsa bo‘lmaydi

* so‘rov yuborilmaydi
* javob kelmaydi

***

### Obuna bo‘lish (subscribe)

```tsx
this.http.get('/api/users').subscribe(data => {
console.log(data);
});

```

Bu quyidagicha tarjima qilinadi:

> “Agar ma’lumot kelsa, menga ber”

***

### Observable bir marta emas, ko‘p marta bo‘lishi mumkin

Masalan:

* tugma har bosilganda signal beradi
* forma har o‘zgarganda yangilanadi

Shuning uchun Observable:

* bitta emas
* **bir nechta ma’lumot yuborishi mumkin**

***

### Observable’ni qanday tasavvur qilish mumkin?

Observable’ni quyidagicha tasavvur qiling:

* Ma’lumot hozir yo‘q
* Keyin keladi
* Kelganda sizga xabar beradi
* Siz kutib o‘tirmaysiz

***

### 5. Error Handling (Xatolarni boshqarish)

#### 5.1 Oddiy error handling

```tsx
loadStudents() {
  this.studentService.getStudents().subscribe({
    next: (data) => {
      this.students = data;
      this.loading = false;
    },
    error: (err) => {
      // Error turini aniqlash
      if (err.status === 404) {
        this.error = 'Ma\\'lumotlar topilmadi';
      } else if (err.status === 500) {
        this.error = 'Server xatosi';
      } else if (err.status === 0) {
        this.error = 'Internetga ulanish yo\\'q';
      } else {
        this.error = 'Noma\\'lum xatolik';
      }

      this.loading = false;
      console.error('Error:', err);
    },
    complete: () => {
      console.log('Request completed');
    }
  });
}

```

#### 5.2 Service da error handling

```tsx
import { catchError, throwError } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class StudentService {

  getStudents(): Observable<Student[]> {
    return this.http.get<Student[]>(this.apiUrl).pipe(
      catchError(this.handleError)
    );
  }

  private handleError(error: any) {
    let errorMessage = '';

    if (error.error instanceof ErrorEvent) {
      // Client-side error
      errorMessage = `Error: ${error.error.message}`;
    } else {
      // Server-side error
      errorMessage = `Error Code: ${error.status}\\nMessage: ${error.message}`;
    }

    console.error(errorMessage);
    return throwError(() => new Error(errorMessage));
  }
}

```

***

### 6. Query Parameters va Headers

#### 6.1 Query parameters bilan so'rov

```tsx
// Misol: /api/students?grade=5&subject=math
getStudentsByGrade(grade: number, subject?: string): Observable<Student[]> {
  let params = new HttpParams().set('grade', grade.toString());

  if (subject) {
    params = params.set('subject', subject);
  }

  return this.http.get<Student[]>(this.apiUrl, { params });
}

```

**Komponentda:**

```tsx
loadStudents() {
  this.studentService.getStudentsByGrade(5, 'math').subscribe({
    next: (data) => {
      this.students = data;
    }
  });
}

```

#### 6.2 Headers bilan ishlash

```tsx
import { HttpHeaders } from '@angular/common/http';

createStudent(student: Student): Observable<Student> {
  const headers = new HttpHeaders({
    'Content-Type': 'application/json',
    'Authorization': 'Bearer your-token-here'
  });

  return this.http.post<Student>(this.apiUrl, student, { headers });
}

```

***

### Nazorat Savollari

1. **HttpClient ishlatish uchun qaysi provider kerak?**
2. **GET so'rovi qanday qilinadi?**
3. **Observable nima va qanday ishlatiladi?**
4. **POST so'rovida qanday ma'lumot yuboriladi?**
5. **Error handling qanday qilinadi?**
6. **Query parameters qanday qo'shiladi?**
7. **Headers qanday yuboriladi?**
8. **DELETE so'rovi qanday ishlaydi?**
9. **Subscribe nima uchun kerak?**

***

### Test Savollari

**1.** `provideHttpClient` **qayerda import qilinadi?**

A) Component

B) Service

C) app.config.ts

D) main.ts

***

**2. GET so'rovi sintaksisi:**

A) `http.get(url)`

B) `http.request('GET', url)`

C) A to'g'ri

D) A va B

***

**3. Observablega obuna bo’lish qanday amalga oshiriladi?**

A) `.subscribe()`

B) `.then()`

C) `.await()`

D) `.get()`

***

**4. POST so'rovi:**

A) `http.post(url, data)`

B) `http.send(url, data)`

C) `http.create(url, data)`

D) `http.add(url, data)`

***

**5. PUT so'rovi nima uchun?**

A) Yangi yaratish

B) Tahrirlash

C) O'chirish

D) O'qish

***

**6. DELETE so'rovi:**

A) `http.delete(url)`

B) `http.remove(url)`

C) `http.destroy(url)`

D) `http.erase(url)`

***

**7. Error callback:**

A) `error: (err) => {}`

B) `catch: (err) => {}`

C) `fail: (err) => {}`

D) `wrong: (err) => {}`

***

**8. Query params qaysi class orqali yaratiladi?**

A) `HttpParams`

B) `QueryParams`

C) `UrlParams`

D) `RequestParams`

***

**9. Subscribeda muvoffaqqiyatli ma’lumot qanday olinadi?**

A) `next: (data) => {}`

B) `success: (data) => {}`

C) `result: (data) => {}`

D) `data: (data) => {}`

***

**10. HTTP status 404 nimani anglatadi?**

A) Server error

B) Not found

C) Success

D) Unauthorized

***

**11. HTTP status 200:**

A) Error

B) Success

C) Not found

D) Redirect

***

**12. RESTful APIlar:**

A) GET, POST, PUT, DELETE

B) Faqat GET

C) Faqat POST

D) Random metodlar

> [QuizBot](https://t.me/QuizBot?start=upx4Vt7v)

***

### Amaliy Topshiriqlar

#### Topshiriq 1: Todo App

O’tgan darslarda qilingan TODO dasturiga Mock API (json server, json placeholder kabi) lar yasab ular uchun Angular service yaratib ushbu API larga so’rov qilish kerak. Ya’ni oldin statik ma’lumotlar bo’lgan bo’lsa endi dynamic ma’lumotlar bo’lishi kerak va real server simulyatsiyasini yordamchi Mock API servicelaridan foydalanish kerak.

***

#### Topshiriq 2: Blog Posts

* Posts ro'yxati
* Post details sahifasi
* Post yaratish formasi
* Post tahrirlash
* Post o'chirish

***

#### Topshiriq 3: Photo Gallery

* Photos ro'yxati (grid layout)
* Album bo'yicha filter
* Search by title
* Click da katta ko'rish

***

> **Darsdan namuna (takrorlash uchun):**

{% embed url="<https://youtu.be/cZyXOBLRdJY>" %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://odilbeks-organization.gitbook.io/angular-ustoz-shogirt/http-va-backend-integration.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
