moving creating of api observable to out service file

master
Matt Huntington 9 years ago
parent 258ec05097
commit 80167be91b

@ -2,23 +2,25 @@ import { Component, OnInit } from '@angular/core';
import { Http } from '@angular/http'; import { Http } from '@angular/http';
import { Subject } from 'rxjs/Subject'; import { Subject } from 'rxjs/Subject';
import { SearchService } from './search.service';
// Observable class extensions // Observable class extensions
import 'rxjs/add/operator/switchMap'; import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/debounceTime'; import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged'; import 'rxjs/add/operator/distinctUntilChanged';
@Component({ @Component({
selector: 'app-search', selector: 'app-search',
templateUrl: './search.component.html', templateUrl: './search.component.html',
styleUrls: ['./search.component.css'] styleUrls: ['./search.component.css'],
providers: [SearchService]
}) })
export class SearchComponent implements OnInit { export class SearchComponent implements OnInit {
results; results;
searchTerms = new Subject<string>(); searchTerms = new Subject<string>();
constructor( constructor(
private heroSearchService: SearchService,
private http: Http private http: Http
) { } ) { }
@ -26,18 +28,11 @@ export class SearchComponent implements OnInit {
this.searchTerms.next(name); this.searchTerms.next(name);
} }
createAPIObservable(name){
return this.http.get('http://swapi.co/api/people/?search=' + name)
.map((response)=>{
return response.json().results;
});
}
ngOnInit() { ngOnInit() {
this.results = this.searchTerms this.results = this.searchTerms
.debounceTime(300) .debounceTime(300)
.distinctUntilChanged() .distinctUntilChanged()
.switchMap(name => this.createAPIObservable(name)); .switchMap(name => this.heroSearchService.createAPIObservable(name));
} }
} }

@ -0,0 +1,15 @@
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class SearchService {
constructor(private http: Http) {}
createAPIObservable(name){
return this.http
.get('http://swapi.co/api/people/?search=' + name)
.map(response=> response.json().results );
}
}
Loading…
Cancel
Save