18 Temmuz 2018 Çarşamba

Spring REST ile Angular ng-select component kullanımı


Merhabalar. Bu yazımda sizlere bir Angular componenti olan ng-select ve daha önceden yazdığım bir Spring REST service kullanarak autocomplete olayını göstereceğim.

ng-select componentinin kurulumu, temel kullanımı ve özellikleri hakkında bilgi almak için buraya 

bakabilirsiniz.

Burada gireceğimiz kullanıcı adı değeri sistemde aranıp filtrelenerek bulunduğu takdirde kullanıcı adının yanı sıra bu kullanıcıya ait tüm bilgileri tutan bir array dolacaktır.

Öncelikle Java tarafında ki servis metodum aşağıda ki gibidir.



@RequestMapping(value = "/filtrele" , method = RequestMethod.GET , produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<List<KullaniciModel>> filterKullanici(@RequestParam String username){
List<KullaniciModel> filteredKullanici = kullaniciService.kullaniciFiltrele(username);
if(filteredKullanici != null && filteredKullanici.size()>0){
return new ResponseEntity<List<KullaniciModel>>(filteredKullanici,HttpStatus.OK);
}
return new ResponseEntity<List<KullaniciModel>>(HttpStatus.NOT_FOUND);
}



ng-select’in html tarafında kullanımı aşağıda ki gibidir.



<div class="form-group">
<label>Kullanıcı Seçiniz</label>
<ng-select [items]="kullanici | async"
 bindLabel="username"
 placeholder="Kullanıcı Ara"
 [hideSelected]="true"
 [multiple]="true"
 typeToSearchText="Kullanıcı adını yazınız"
 notFoundText="Kullanıcı Bulunamadı"
 [loading]="kullaniciLoading"
 [typeahead]="kullaniciInput"
 [(ngModel)]="selectedUser">
</ng-select>
</div>



Component tarafında ise aşağıda ki gibi kullanılır.



import { Component, OnInit } from '@angular/core';

import { AuthService } from '../../auth/auth.service';
import { Observable, of, Subject,concat } from 'rxjs';
import { catchError, debounceTime, distinctUntilChanged, map, tap, switchMap } from 'rxjs/operators';

@Component({
selector: 'app-rol',
templateUrl: './rol.component.html',
styleUrls: ['./rol.component.css']
})
export class RolComponent implements OnInit {

kullanici: Observable<any>;
kullaniciLoading = false;
kullaniciInput = new Subject<string>();
selectedUser: any[];



constructor(private auhtService: AuthService { }

ngOnInit() {
 this.loadKullanici();
}

private loadKullanici() {
 this.kullanici = concat(
  of([]), // default items
    this.kullaniciInput.pipe(
    debounceTime(200),
    distinctUntilChanged(),
    tap(() => this.kullaniciLoading = true),
       switchMap(term => this.auhtService.getKullaniciFiltrele(term).pipe(
          catchError(() => of([])), // empty list on error
          tap(() => this.kullaniciLoading = false)
       ))
     )
   );
}
}



Angular tarafında Java servisini çağırışım ise aşağıda ki gibidir.

getKullaniciFiltrele(username:string):Observable<any>{

   return this.http.get(this.apiUrl + 'api/kullanici/filtrele?username='+username);
}


Componentin autocomplete kullanımına dair ekran görüntüleri aşağıda ki gibidir.