【问题标题】:Passing parameters to http.* in Angular2在Angular2中将参数传递给http.*
【发布时间】:2017-08-12 19:09:31
【问题描述】:

我的问题似乎很基本,但我无法弄清楚。 我有一个Angular2 服务。它看起来有点像下面

 return this.http
        .get("localhost:300/users/:id" )
        .toPromise().then(response => response.json() as User)
        .catch(this.handleError);

当我在组件中调用此服务时,如何在我的 API URL localhost:300/users/:id 中设置 id 的值。

希望我清楚这一点。

【问题讨论】:

  • 也许将其作为参数传递? .get("localhost:300/users/:" + id )
  • 作为返回 this 的函数的参数发送..
  • @echonax 有没有办法/方法,我只传递 URL 和值,然后返回设置参数的 URL?
  • @Thabung ehm 看看下面的答案,我猜你说的对吗?

标签: angular http angular2-http


【解决方案1】:

我正在为此创建一个助手类。如果您有更好的想法,请提出建议。

import { Injectable } from '@angular/core';
@Injectable()
export class HelperService {
    public injectParamsInUrl(urlString: string, paramObject: any):string {
        if (typeof paramObject == 'undefined') {
            return urlString;
        }
        for (let i in paramObject) {
            let stringified = JSON.stringify(paramObject[i]);
            urlString = urlString.replace(":" + i, stringified);
        }
        return urlString;
    }
}

【讨论】:

    【解决方案2】:

    在 Angular 2 中我编写了这个服务:

    export abstract class RestResource {
    
        protected url = REST_URL;
        protected abstract action: string;
    
        protected router:Router;
        protected http:Http;
        protected state:GlobalState;
        protected injector: Injector;
    
    
    
        protected constructor(injector: Injector) {
    
            this.router = injector.get(Router);
            this.http = injector.get(Http);
            this.state= injector.get(GlobalState);
    
            this.injector = injector;
    
        }
    
        protected get(params?: URLSearchParams, action?: string): Observable<Object> {
    
            let currentAction = action != null ? action : this.action;
            let options = new RequestOptions();
    
            if(params)
                options.search = params;
    
            return this.http.get(this.url + currentAction, options)
                .map(this.extractData)
                .catch((error):ErrorObservable<any> => {
                    return this.handleError(error)
                })
        }
    
        protected post(data: any, action?: string,params?:URLSearchParams): Observable<Object> {
    
    
            let currentAction = action != null ? action : this.action;
            let options = new RequestOptions();
            if(params)
            {
                options.search = params;
            }
    
            return this.http.post(this.url + currentAction, data,options)
                .map(this.extractData)
                .catch((error):ErrorObservable<any> => {
                    return this.handleError(error)
                });
        }
    
    
        protected delete(id:string,action?:string):Observable<boolean>
        {
    
    
            let currentAction = action != null ? action : this.action;
            let options = new RequestOptions();
            let search = new URLSearchParams();
    
            search.append('id',id);
            options.search = search;
    
            return this.http.delete(this.url + currentAction,options)
                .map(this.extractData)
                .catch((error):ErrorObservable<any> => {
                    return this.handleError(error)
                });
        }
    
    
    
    
    
        protected put(id:string,data: any, action?: string): Observable<Object> {
    
    
            let options = new RequestOptions();
            let search = new URLSearchParams();
            let currentAction = action != null ? action : this.action;
    
            search.append('id',id);
            options.search = search;
            options.method = 'PUT';
            options.body = data;
    
            return this.http.request(this.url + currentAction, options)
                .map(this.extractData)
                .catch((error):ErrorObservable<any> => {
                    return this.handleError(error)
                });
        }
    
        protected extractData(data: Response) {
            return data.json();
        }
    
        protected handleError(error: Response | any):ErrorObservable<any> {
    
    
            let errorHandler = ErrorHandlerFactory.createErrorHandler(error.status,this.injector);
            return errorHandler.handleError(error);
    
        }
    
    
    }
    

    接下来我在 AppModule 中编写

    providers: [
        {provide:RequestOptions, useClass: RestCredentialsRequestOptions },
    ]
    

    类:

        @Injectable()
    export class RestCredentialsRequestOptions extends BaseRequestOptions
    {
    
    
    
        constructor () {
            super();
                this.withCredentials = true;
                this.headers.append('Content-Type', 'application/json');
    
    
        }
    
    
        merge(options?: RequestOptionsArgs): RequestOptions {
    
            if(options.search && (<URLSearchParams> options.search).has('id'))
            {
                options.url+='/'+(<URLSearchParams> options.search).get('id');
                (<URLSearchParams> options.search).delete('id');
            }
    
            return super.merge(options);
        }
    }
    

    所以只需在请求之前将 id 从 params 替换为 /:id

    资源类示例:

     @Injectable()
    export class ConversationsService extends RestResource{
    
        action: string  = "/conversations/service";
    
        constructor(injector: Injector) {
            super(injector);
        }
    
        public list(values:URLSearchParams):Observable<any>
        {
            return this.get(values);
        }
    
        public details(id:string,searchParams?: URLSearchParams):Observable<any>
        {
            let params = new URLSearchParams();
    
            if (searchParams)
                params = searchParams;
            params.append('id', id);
            return this.get(params);
        }
    
    
        public create(model:Object):Observable<any>
        {
            return this.post(model);
        }
    
    
    
        public remove(id:string):Observable<any>
        {
            return this.delete(id);
        }
    
    }
    

    【讨论】:

      【解决方案3】:
      getApiValue(id){
          return this.http
          .get("localhost:300/users/:"+id )
          .toPromise().then(response => response.json() as User)
          .catch(this.handleError);
      }
      

      【讨论】:

      • 不要使用.toPromise().then(response =&gt; response.json() as User),也可以使用subscribe
      • 有没有一种方法/方法,我只传递 URL 和值,然后返回设置了参数的 URL?
      猜你喜欢
      • 2016-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-31
      相关资源
      最近更新 更多