首页 文章

Angular2 http使用Observables和动态url参数获取请求 . 如何?

提问于
浏览
0

将此angular2服务从Observable的官方文档中获取,尝试修改为可以传递给 app/heroes/{{country}} 这样的基础 heroesUrl 动态参数并使用它像

getHeroes(country) {}

import { Injectable }     from '@angular/core';
import { Http, Response } from '@angular/http';
import { Hero }           from './hero';
import { Observable }     from 'rxjs/Observable';
@Injectable()
export class HeroService {
  constructor (private http: Http) {}
  private heroesUrl = 'app/heroes';  // URL to web API
  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: any) {
    // In a real world app, we might use a remote logging infrastructure
    // We'd also dig deeper into the error to get a better message
    let errMsg = (error.message) ? error.message :
      error.status ? `${error.status} - ${error.statusText}` : 'Server error';
    console.error(errMsg); // log to console instead
    return Observable.throw(errMsg);
  }
}

我该怎么办?

1 回答

  • 1

    如果我理解你的观点,我认为你只需要做一些事情,

    getHeroes(country) {}
    
    
    export class HeroService {
      constructor (private http: Http) {}
      private heroesUrl = 'app/heroes';  // URL to web API
      getHeroes (country): Observable<Hero[]> {               //<-----added parameter
        return this.http.get(this.heroesUrl + '/' + country)  //<-----changed
                        .map(this.extractData)
                        .catch(this.handleError);
      }
      ...
      ...
    }
    

相关问题