Angular uygulamasına servisler ekleyin

Bu eğitim dersi, bir Angular servisi oluşturmayı ve bağımlılık enjeksiyonu kullanarak uygulamanıza dahil etmeyi gösterir.

Neler öğreneceksiniz

Uygulamanız, verilerinizi uygulamanıza sunan bir servise sahiptir. Bu dersin sonunda, servis verileri yerel, statik verilerden okur. İlerideki bir derste, servisi bir web servisinden veri alacak şekilde güncelleyeceksiniz.

Servislerin kavramsal önizlemesi

Bu eğitim, Angular servisleri ve bağımlılık enjeksiyonunu tanıtır.

Angular servisleri

Angular servisleri, uygulamanızdaki birden fazla bileşen tarafından kullanılabilen Angular uygulama verilerini ve işlevlerini ayırmanız için bir yol sağlar. Birden fazla bileşen tarafından kullanılabilmesi için, bir servisin enjekte edilebilir olması gerekir. Enjekte edilebilir olan ve bir bileşen tarafından kullanılan servisler, o bileşenin bağımlılıkları haline gelir. Bileşen bu servislere bağımlıdır ve onlar olmadan çalışamaz.

Bağımlılık enjeksiyonu

Bağımlılık enjeksiyonu, bir uygulamanın bileşenlerinin bağımlılıklarını ve diğer bileşenlerin kullanabileceği servisleri yöneten mekanizmadır.

  1. Uygulamanız için yeni bir servis oluşturun

    Bu adım, uygulamanız için enjekte edilebilir bir servis oluşturur.

    IDE'nizin Terminal bölmesinde:

    1. Proje dizininizde, first-app dizinine gidin.

    2. first-app dizininde, yeni servisi oluşturmak için bu komutu çalıştırın.

      ng generate service housing --skip-tests
    3. Uygulamayı derlemek ve http://localhost:4200 adresinde sunmak için ng serve komutunu çalıştırın.

    4. Uygulamanın hatasız derlendiğini doğrulayın. Bir sonraki adıma geçmeden önce tüm hataları düzeltin.

  2. Yeni servise statik veri ekleyin

    Bu adım, yeni servisinize bazı örnek veriler ekler. İlerideki bir derste, statik verileri gerçek bir uygulamada yapabileceğiniz gibi veri almak için bir web arayüzüyle değiştireceksiniz. Şimdilik, uygulamanızın yeni servisi, şimdiye kadar Home bileşeninde yerel olarak oluşturulan verileri kullanır.

    IDE'nizin Edit bölmesinde:

    1. src/app/home/home.ts dosyasından, Home bileşenindeki housingLocationList değişkenini ve dizi değerini kopyalayın.

    2. src/app/housing.service.ts dosyasında:

      1. HousingService sınıfı içinde, önceki adımda Home bileşeninden kopyaladığınız değişkeni yapıştırın.

      2. HousingService sınıfı içinde, az önce kopyaladığınız veriden sonra bu fonksiyonları yapıştırın. Bu fonksiyonlar, bağımlılıkların servisin verilerine erişmesini sağlar.

        Service functions in src/app/housing.service.ts

        import {Injectable} from '@angular/core';
        import {HousingLocationInfo} from './housinglocation';
        @Injectable({
          providedIn: 'root',
        })
        export class HousingService {
          readonly baseUrl = 'https://angular.dev/assets/images/tutorials/common';
        
          protected housingLocationList: HousingLocationInfo[] = [
            {
              id: 0,
              name: 'Acme Fresh Start Housing',
              city: 'Chicago',
              state: 'IL',
              photo: `${this.baseUrl}/bernard-hermant-CLKGGwIBTaY-unsplash.jpg`,
              availableUnits: 4,
              wifi: true,
              laundry: true,
            },
            {
              id: 1,
              name: 'A113 Transitional Housing',
              city: 'Santa Monica',
              state: 'CA',
              photo: `${this.baseUrl}/brandon-griggs-wR11KBaB86U-unsplash.jpg`,
              availableUnits: 0,
              wifi: false,
              laundry: true,
            },
            {
              id: 2,
              name: 'Warm Beds Housing Support',
              city: 'Juneau',
              state: 'AK',
              photo: `${this.baseUrl}/i-do-nothing-but-love-lAyXdl1-Wmc-unsplash.jpg`,
              availableUnits: 1,
              wifi: false,
              laundry: false,
            },
            {
              id: 3,
              name: 'Homesteady Housing',
              city: 'Chicago',
              state: 'IL',
              photo: `${this.baseUrl}/ian-macdonald-W8z6aiwfi1E-unsplash.jpg`,
              availableUnits: 1,
              wifi: true,
              laundry: false,
            },
            {
              id: 4,
              name: 'Happy Homes Group',
              city: 'Gary',
              state: 'IN',
              photo: `${this.baseUrl}/krzysztof-hepner-978RAXoXnH4-unsplash.jpg`,
              availableUnits: 1,
              wifi: true,
              laundry: false,
            },
            {
              id: 5,
              name: 'Hopeful Apartment Group',
              city: 'Oakland',
              state: 'CA',
              photo: `${this.baseUrl}/r-architecture-JvQ0Q5IkeMM-unsplash.jpg`,
              availableUnits: 2,
              wifi: true,
              laundry: true,
            },
            {
              id: 6,
              name: 'Seriously Safe Towns',
              city: 'Oakland',
              state: 'CA',
              photo: `${this.baseUrl}/phil-hearing-IYfp2Ixe9nM-unsplash.jpg`,
              availableUnits: 5,
              wifi: true,
              laundry: true,
            },
            {
              id: 7,
              name: 'Hopeful Housing Solutions',
              city: 'Oakland',
              state: 'CA',
              photo: `${this.baseUrl}/r-architecture-GGupkreKwxA-unsplash.jpg`,
              availableUnits: 2,
              wifi: true,
              laundry: true,
            },
            {
              id: 8,
              name: 'Seriously Safe Towns',
              city: 'Oakland',
              state: 'CA',
              photo: `${this.baseUrl}/saru-robert-9rP3mxf8qWI-unsplash.jpg`,
              availableUnits: 10,
              wifi: false,
              laundry: false,
            },
            {
              id: 9,
              name: 'Capital Safe Towns',
              city: 'Portland',
              state: 'OR',
              photo: `${this.baseUrl}/webaliser-_TPTXZd9mOo-unsplash.jpg`,
              availableUnits: 6,
              wifi: true,
              laundry: true,
            },
          ];
        
          getAllHousingLocations(): HousingLocationInfo[] {
            return this.housingLocationList;
          }
        
          getHousingLocationById(id: number): HousingLocationInfo | undefined {
            return this.housingLocationList.find((housingLocation) => housingLocation.id === id);
          }
        }
        

        Bu fonksiyonlara ilerideki bir derste ihtiyacınız olacak. Şimdilik, bu fonksiyonların belirli bir HousingLocation'ı id'ye göre veya tüm listeyi döndürdüğünü anlamak yeterlidir.

      3. HousingLocation için dosya düzeyinde bir import ekleyin.

        Import HousingLocation type in src/app/housing.service.ts

        import {Injectable} from '@angular/core';
        import {HousingLocationInfo} from './housinglocation';
        @Injectable({
          providedIn: 'root',
        })
        export class HousingService {
          readonly baseUrl = 'https://angular.dev/assets/images/tutorials/common';
        
          protected housingLocationList: HousingLocationInfo[] = [
            {
              id: 0,
              name: 'Acme Fresh Start Housing',
              city: 'Chicago',
              state: 'IL',
              photo: `${this.baseUrl}/bernard-hermant-CLKGGwIBTaY-unsplash.jpg`,
              availableUnits: 4,
              wifi: true,
              laundry: true,
            },
            {
              id: 1,
              name: 'A113 Transitional Housing',
              city: 'Santa Monica',
              state: 'CA',
              photo: `${this.baseUrl}/brandon-griggs-wR11KBaB86U-unsplash.jpg`,
              availableUnits: 0,
              wifi: false,
              laundry: true,
            },
            {
              id: 2,
              name: 'Warm Beds Housing Support',
              city: 'Juneau',
              state: 'AK',
              photo: `${this.baseUrl}/i-do-nothing-but-love-lAyXdl1-Wmc-unsplash.jpg`,
              availableUnits: 1,
              wifi: false,
              laundry: false,
            },
            {
              id: 3,
              name: 'Homesteady Housing',
              city: 'Chicago',
              state: 'IL',
              photo: `${this.baseUrl}/ian-macdonald-W8z6aiwfi1E-unsplash.jpg`,
              availableUnits: 1,
              wifi: true,
              laundry: false,
            },
            {
              id: 4,
              name: 'Happy Homes Group',
              city: 'Gary',
              state: 'IN',
              photo: `${this.baseUrl}/krzysztof-hepner-978RAXoXnH4-unsplash.jpg`,
              availableUnits: 1,
              wifi: true,
              laundry: false,
            },
            {
              id: 5,
              name: 'Hopeful Apartment Group',
              city: 'Oakland',
              state: 'CA',
              photo: `${this.baseUrl}/r-architecture-JvQ0Q5IkeMM-unsplash.jpg`,
              availableUnits: 2,
              wifi: true,
              laundry: true,
            },
            {
              id: 6,
              name: 'Seriously Safe Towns',
              city: 'Oakland',
              state: 'CA',
              photo: `${this.baseUrl}/phil-hearing-IYfp2Ixe9nM-unsplash.jpg`,
              availableUnits: 5,
              wifi: true,
              laundry: true,
            },
            {
              id: 7,
              name: 'Hopeful Housing Solutions',
              city: 'Oakland',
              state: 'CA',
              photo: `${this.baseUrl}/r-architecture-GGupkreKwxA-unsplash.jpg`,
              availableUnits: 2,
              wifi: true,
              laundry: true,
            },
            {
              id: 8,
              name: 'Seriously Safe Towns',
              city: 'Oakland',
              state: 'CA',
              photo: `${this.baseUrl}/saru-robert-9rP3mxf8qWI-unsplash.jpg`,
              availableUnits: 10,
              wifi: false,
              laundry: false,
            },
            {
              id: 9,
              name: 'Capital Safe Towns',
              city: 'Portland',
              state: 'OR',
              photo: `${this.baseUrl}/webaliser-_TPTXZd9mOo-unsplash.jpg`,
              availableUnits: 6,
              wifi: true,
              laundry: true,
            },
          ];
        
          getAllHousingLocations(): HousingLocationInfo[] {
            return this.housingLocationList;
          }
        
          getHousingLocationById(id: number): HousingLocationInfo | undefined {
            return this.housingLocationList.find((housingLocation) => housingLocation.id === id);
          }
        }
        
    3. Uygulamanın hatasız derlendiğini doğrulayın. Bir sonraki adıma geçmeden önce tüm hataları düzeltin.

  3. Yeni servisi Home bileşenine enjekte edin

    Bu adım, yeni servisi uygulamanızın Home bileşenine enjekte eder, böylece uygulama verilerini bir servisten okuyabilir. İlerideki bir derste, statik verileri gerçek bir uygulamada yapabileceğiniz gibi veri almak için canlı bir veri kaynağıyla değiştireceksiniz.

    IDE'nizin Edit bölmesinde, src/app/home/home.ts dosyasında:

    1. src/app/home/home.ts dosyasının en üstünde, @angular/core'dan içe aktarılan öğelere inject'i ekleyin. Bu, inject fonksiyonunu Home sınıfına aktaracaktır.

      Update to src/app/home/home.ts

      import {Component, inject} from '@angular/core';
      import {HousingLocation} from '../housing-location/housing-location';
      import {HousingLocationInfo} from '../housinglocation';
      import {HousingService} from '../housing.service';
      @Component({
        selector: 'app-home',
        imports: [HousingLocation],
        template: `
          <section>
            <form>
              <input type="text" placeholder="Filter by city" />
              <button class="primary" type="button">Search</button>
            </form>
          </section>
          <section class="results">
            @for (housingLocation of housingLocationList; track $index) {
              <app-housing-location [housingLocation]="housingLocation" />
            }
          </section>
        `,
        styleUrls: ['./home.css'],
      })
      export class Home {
        housingLocationList: HousingLocationInfo[] = [];
        housingService: HousingService = inject(HousingService);
      
        constructor() {
          this.housingLocationList = this.housingService.getAllHousingLocations();
        }
      }
      
    2. HousingService için yeni bir dosya düzeyinde import ekleyin:

      Add import to src/app/home/home.ts

      import {Component, inject} from '@angular/core';
      import {HousingLocation} from '../housing-location/housing-location';
      import {HousingLocationInfo} from '../housinglocation';
      import {HousingService} from '../housing.service';
      @Component({
        selector: 'app-home',
        imports: [HousingLocation],
        template: `
          <section>
            <form>
              <input type="text" placeholder="Filter by city" />
              <button class="primary" type="button">Search</button>
            </form>
          </section>
          <section class="results">
            @for (housingLocation of housingLocationList; track $index) {
              <app-housing-location [housingLocation]="housingLocation" />
            }
          </section>
        `,
        styleUrls: ['./home.css'],
      })
      export class Home {
        housingLocationList: HousingLocationInfo[] = [];
        housingService: HousingService = inject(HousingService);
      
        constructor() {
          this.housingLocationList = this.housingService.getAllHousingLocations();
        }
      }
      
    3. Home bileşeninden housingLocationList dizi girişlerini silin ve housingLocationList'e boş dizi ([]) değerini atayın. Birkaç adım sonra verileri HousingService'ten çekmek için kodu güncelleyeceksiniz.

    4. Home bileşeninde, yeni servisi enjekte etmek ve uygulama için verileri başlatmak üzere aşağıdaki kodu ekleyin. constructor, bu bileşen oluşturulduğunda çalışan ilk fonksiyondur. constructor içindeki kod, housingLocationList'e getAllHousingLocations çağrısından dönen değeri atayacaktır.

      Initialize data from service in src/app/home/home.ts

      import {Component, inject} from '@angular/core';
      import {HousingLocation} from '../housing-location/housing-location';
      import {HousingLocationInfo} from '../housinglocation';
      import {HousingService} from '../housing.service';
      @Component({
        selector: 'app-home',
        imports: [HousingLocation],
        template: `
          <section>
            <form>
              <input type="text" placeholder="Filter by city" />
              <button class="primary" type="button">Search</button>
            </form>
          </section>
          <section class="results">
            @for (housingLocation of housingLocationList; track $index) {
              <app-housing-location [housingLocation]="housingLocation" />
            }
          </section>
        `,
        styleUrls: ['./home.css'],
      })
      export class Home {
        housingLocationList: HousingLocationInfo[] = [];
        housingService: HousingService = inject(HousingService);
      
        constructor() {
          this.housingLocationList = this.housingService.getAllHousingLocations();
        }
      }
      
    5. src/app/home/home.ts dosyasındaki değişiklikleri kaydedin ve uygulamanızın hatasız derlendiğini doğrulayın. Bir sonraki adıma geçmeden önce tüm hataları düzeltin.

SUMMARY: Bu derste, uygulamanıza bir Angular servisi eklediniz ve onu Home sınıfına enjekte ettiniz. Bu, uygulamanızın verilerini nasıl aldığını bölümlere ayırır. Şimdilik, yeni servis verilerini statik bir veri dizisinden alır. İlerideki bir derste, servisi bir API uç noktasından veri alacak şekilde yeniden düzenleyeceksiniz.

Bu derste ele alınan konular hakkında daha fazla bilgi için: