将参数传递给Angular2中的http。*

时间:2017-03-21 08:23:25

标签: angular http angular2-http

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

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

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

希望我能清楚这一点。

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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

所以在请求之前简单地将para从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);
    }

}

答案 2 :(得分:0)

我正在创建一个帮助类。如果你有,请建议任何更好的主意。

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