Angular ရှိ Service အသုံးပြုခြင်း
ယခင်သင်ခန်းစာတွင် ကျွန်ုပ်တို့၏ကိုယ်ပိုင်
Service DataService ကို ဖန်တီးခဲ့ကြသည်။
ယခု ၎င်းကို Component အတွင်းသို့ တင်သွင်းကြည့်ရအောင်။
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { DataService } from './data.service'; // ဤနေရာ
Decorator @Component အတွင်းရှိ property
providers တွင် ကျွန်ုပ်တို့၏ Service ကို ဖော်ပြရန် လိုအပ်ပါသည်။
@Component({
.....
providers: [ DataService ] // ဤနေရာ
})
ယခု ကျွန်ုပ်တို့သည် Dependency Injection (dependency injection) ဟုခေါ်သော အထူးနည်းလမ်းကို အသုံးပြုပါမည်။ ၎င်း၏အဓိပ္ပါယ်မှာ Component ၏ constructor အတွင်းသို့ ကျွန်ုပ်တို့၏ Service ကို parameter အဖြစ် ပေးပို့နိုင်ပြီး ထို့နောက် ၎င်းသည် ကျွန်ုပ်တို့ Component ၏ private property အတွင်းသို့ အလိုအလျောက် ရောက်ရှိလာမည်ဖြစ်သည်။ ကုဒ်အတွင်းကြည့်ပါ။
export class AppComponent {
constructor(private dataService: DataService) { // dependency ကို inject လုပ်သည်
console.log(this.dataService); // service သည် private property အတွင်းရှိသည်
}
}
ကျွန်ုပ်တို့၏ Service အတွက် Dependency Injection အလုပ်လုပ်နေခြင်းမှာ
ကျွန်ုပ်တို့သည် ယခင်က Decorator Injectable ကို ၎င်းအား သုံးစွဲထားသောကြောင့်ဖြစ်သည်။
ယခု Component class ၏ constructor အတွင်းတွင် ကျွန်ုပ်တို့၏ Service မှ သက်ဆိုင်ရာမှ method ကိုခေါ်၍ ဒေတာများကို ရယူကြည့်ရအောင်။
export class AppComponent {
public data: string[] = [];
constructor(private dataService: DataService) {
this.data = this.dataService.getData();
}
}
ရယူထားသော ဒေတာများကို Component ၏ template အတွင်းတွင် ထုတ်ပြကြည့်ရအောင်။
<ol>
<li *ngFor="elem of data">
{{ elem }}
</li>
</ol>
သင်၏ Service မှ ပစ္စည်းများကို Component အတွင်းရယူ၍ Component ၏ template အတွင်းတွင် ထုတ်ပြပါ။
သင်၏ Service အတွင်း ပစ္စည်းအသစ်ထည့်သွင်းရန် Method တစ်ခု ပြုလုပ်ပါ။ Component အတွင်း ခလုတ်တစ်ခု ပြုလုပ်ပါ။ ထိုခလုတ်ကို နှိပ်လိုက်သောအခါ ပစ္စည်းအသစ်တစ်ခု ထပ်မံပေါင်းထည့်သွားပါမည်။
Input နှစ်ခုနှင့် ခလုတ်တစ်ခု ပါဝင်သော Form တစ်ခု ပြုလုပ်ပါ။ ထိုခလုတ်ကို နှိပ်လိုက်သောအခါ ပစ္စည်းအသစ်တစ်ခု ထပ်မံပေါင်းထည့်သွားပါမည်။