2017-12-18 159 views
0

我正在编写一个SDK,我正在使用一个方法callApi来完成建立一个http请求的重复工作。如何动态使用接口?

这就是:

private callApi(method: string, route: string, options?: object, body?: object) { 

// build up query parameters 
let params = new HttpParams(); 
if (options) { 
    _.forOwn(options, (val, key) => { 
    params.append(key, val); 
    }) 
} 

// get and delete don't have a body 
if (method == 'get' || method === 'delete') { 
    return this.http[method](this.apiurl + route, { 
    params: params, 
    headers: new HttpHeaders().set('Authorization', 'Bearer ' + this.GetToken()) 
    }) 
} else { 
    return this.http[method](this.apiurl + route, body, { 
    params: params, 
    headers: new HttpHeaders().set('Authorization', 'Bearer ' + this.GetToken()) 
    }) 
} 
} 

我想用另一种方法来调用它,例如:

ListCategories: (options?: object) => { 
    return this.callApi('get', '/me/categories', options) 
}, 

但我也想莫名其妙地调用它与方法一个特定于调用它的方法的接口。

因此,例如,当我调用ListCategories时,我希望这个泛型方法callApi以某种方式知道特定于列出类别的接口。我该如何做到这一点?我尝试过传递接口,但是当我阅读接口时,它看起来并不像它们在运行时存在的那样。

+0

使用泛型'' – Aravind

+0

但我想要一个特定的接口。我更新了调用它的方法:ListCategories:(options ?: object):Observable 这似乎是我想要的。所以基本上调用它的方法定义了接口,callApi没有。我认为没关系。可能不是最佳做法? –

+2

*因为我正在阅读有关接口,它看起来不像它们在运行时存在* - 它们肯定不会。你可能有XY问题。考虑提供你想要实现的内容的详细解释。这些接口是什么以及callApi应该如何受到它们的影响。 – estus

回答

0

好像你正在寻找像拦截器一样的东西。如果是这种情况,你可以使用角拦截器。

否则找SOLN使用http.request方法下面给出的。

export class CustomHttpService { 
    private apiurl: string; 

    constructor(private http: Http) { 
    // test 
    } 
    public callApi<T>(method: string, route: string, options?: object, body?: object): Observable<T> { 
    const params = new HttpParams(); 
    if (options) { 
     _.forOwn (options, (val, key) => { 
     params.append (key, val); 
     }); 
    } 
    const headers = new Headers(); 
    headers.set ('Authorization', 'Bearer ' + this.getTaken()) 
    return this.http.request (this.apiurl + route, { 
     method, 
     body, 
     params, 
     headers 
    }).map ((response) => response.json()); 
    } 
    private getTaken() { 
    return 'xxxx'; 
    } 
}