Angular2 http获取带有Observables和动态url参数的请求。如何?

德罗查

将此Angle2服务从Observable的官方文档中获取,尝试进行修改以将其heroesUrl动态传递给像这样的基本动态参数app/heroes/{{country}},并像

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);
  }
}

我该怎么做?

小尼克

我认为,只要我了解您的观点,您就需要做一些事情,

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);
  }
  ...
  ...
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章