【问题标题】:Angular2 http get request with Observables and dynamic url params. How to?Angular2 http 获取带有 Observables 和动态 url 参数的请求。如何?
【发布时间】:2017-01-16 06:49:59
【问题描述】:

这个 angular2 服务取自带有 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);
  }
}

我该怎么做?

【问题讨论】:

    标签: http url angular get request


    【解决方案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);
      }
      ...
      ...
    }
    

    【讨论】:

      猜你喜欢
      • 2016-12-27
      • 1970-01-01
      • 2016-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-28
      • 2017-10-07
      • 1970-01-01
      相关资源
      最近更新 更多