Benutzer:MovGP0/Angular/HTTP Client

aus Wikipedia, der freien Enzyklopädie
Zur Navigation springen Zur Suche springen
   MovGP0        Über mich        Hilfen        Artikel        Weblinks        Literatur        Zitate        Notizen        Programmierung        MSCert        Physik      

Angular HTTP Client

[Bearbeiten | Quelltext bearbeiten]
import { Injectable }              from '@angular/core';
import { Http, Response }          from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import { Hero } from './hero';

@Injectable()
export class HeroRepository
{
  private heroesUrl = 'app/heroes'; 
  constructor (private http: Http) {}

  getHeroes () : Observable<Hero[]> {
    return this.http.get(this.heroesUrl)
                    .map(this.extractData)
                    .catch(this.handleError);
  }

  private extractData(res: Response) {
    let body = res.json();
    return body.data || { };
  }

  private handleError (error: Response | any) {
    // TODO: use a remote logging infrastructure
    var errorMessage = getErrorMessage(error);
    console.error(errorMessage);
    return Observable.throw(errMsg);
  }

  private getErrorMessage(error: Response | any) : string {
    if (error instanceof Response) {
      const body = error.json() || '';
      const err = body.error || JSON.stringify(body);
      return `${error.status} - ${error.statusText || ''} ${err}`;
    } 
    
    return error.message ? error.message : error.toString();
  }
}
[Bearbeiten | Quelltext bearbeiten]
search.html
    <h1>Smarter Wikipedia Demo</h1>
    <p>Search when typing stops</p>
    <input #term (keyup)="search(term.value)"/>
    <ul>
      <li *ngFor="let item of items | async">{{item}}</li>
    </ul>
Component
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/switchMap';
import { Subject } from 'rxjs/Subject';
import { WikipediaService } from './wikipedia.service';

@Component({
  moduleId: module.id,
  selector: 'my-wiki-smart',
  templateUrl: 'search.html',
  providers: [ WikipediaService ]
})
export class WikiSmartComponent implements OnInit {
  items: Observable<string[]>;
  private searchTermStream = new Subject<string>();
  
  constructor (private wikipediaService: WikipediaService) {
  }
  
  search(term: string) { 
    this.searchTermStream.next(term); 
  }
  
  ngOnInit() {
    this.items = this.searchTermStream
      .debounceTime(300)
      .distinctUntilChanged()
      .switchMap((term: string) => this.wikipediaService.search(term));
  }
}

|}