首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在angular + typescript中以类型安全的方式将$http拦截器与自定义字段一起使用

在angular + typescript中以类型安全的方式将$http拦截器与自定义字段一起使用
EN

Stack Overflow用户
提问于 2015-12-09 20:08:21
回答 1查看 744关注 0票数 1

我目前实现了一个角度$http拦截器,根据本地存储值为请求添加自定义头部(我需要在我的应用程序中实现一个"Su“功能)

我需要在一些特殊的请求上“停用”这个行为(=我需要能够在每个请求的基础上配置它),我想通过在调用我的$http方法时添加一个额外的配置参数来实现这一点。

拦截器看起来像这样:

代码语言:javascript
复制
$httpProvider.interceptors.push((localStorageService: ng.local.storage.ILocalStorageService) => {
    return {
        request: (config: ng.IRequestShortcutConfig) => {
            var su = localStorageService.get<string>('Su');
            if(su && !("avoidSudo" in config)){
                config.headers.Su = `{ "principal": "${su}" }`;
            }
            return config;
        }
    }
});

当我想停用我的"su“特性时,$http服务调用如下所示:

代码语言:javascript
复制
this.$http.get('/api/sessions/current', { avoidSudo: true })

在TypeScript1.6中,这段代码没有编译,因为$http.get()的第二个参数应该是一个ng.IRequestShortcutConfig,它显然不包含我的特定avoidSudo字段(Typescript编译错误就在这里)

我可以通过将{ avoidSudo: true }替换为<any>{ avoidSudo: true }来解决编译错误,但从类型安全性的角度来看,这显然不太理想

为此,我尝试创建一个新的SkipSudoRequestShortcutConfig专用类(实现ng.IRequestShortcutConfig)。如下所示:

代码语言:javascript
复制
module mymodule {
  export class SkipSudoRequestShortcutConfig implements ng.IRequestShortcutConfig { 
    // For testing purposes only
    _noSudo: boolean;
    constructor(
            public params?: any,
            public headers?: any,
            public xsrfHeaderName?: string,
            public xsrfCookieName?: string,
            public cache?: any,
            public withCredentials?: boolean,
            public data?: any,
            public transformRequest?: any,
            public transformResponse?: any,
            public timeout?: any,
            public responseType?: string
    ){
        this._noSudo = true;
    }
  }
}

如下所示:

代码语言:javascript
复制
var config = new SkipSudoRequestShortcutConfig();
console.log(config instanceof SkipSudoRequestShortcutConfig); // Shows true
console.log(config._noSudo); // Shows true
this.$http.get('/api/sessions/current', config)

在拦截器中像这样使用:

代码语言:javascript
复制
        request: (config: ng.IRequestShortcutConfig) => {
            var su = localStorageService.get<string>('Su');
            console.log(config instanceof SkipSudoRequestShortcutConfig); // Shows *false* :(
            // console.log(config._noSudo); // Doesn't compile, but if executed at runtime with a breakpoint, it works and display true
            if(su && !(config instanceof mymodule.SkipSudoRequestShortcutConfig)){
                config.headers.Su = `{ "principal": "${su}" }`;
            }
            return config;
        }

但是在request处理程序中,instanceof测试是错误的。

我想知道实现这个目标的最好/最简单的方法是什么。您是否认为ng.IRequestShortcutConfig缺少一个特殊的config字段,允许将来自$http调用的自定义字段放到拦截器处理程序中?

提前谢谢你,

EN

回答 1

Stack Overflow用户

发布于 2016-08-03 20:32:22

重要的是要记住,TypeScript中的类型只是“类型助手”,在转换为javascript时会被移除。因此,您不需要实现新的$http服务。相反,你可以创建一个新的类型来满足你的需求。

实际上,这是因为缺少角度类型定义。

您可以通过创建以下接口来修复此问题。

代码语言:javascript
复制
export interface IRequestShortcutConfigWithCustomConfig extends ng.IRequestShortcutConfig {
    [key: string]: any;
}

我使用的是字典样式的类型,因为它可以支持所有内容。但是如果你不想要一个通用的定义,你可以把它改为avoidSudo: boolean;

代码语言:javascript
复制
export interface IHttpServiceWithCustomConfig extends ng.IHttpService {
    get<T>(url: string, config?: IRequestShortcutConfigWithCustomConfig): ng.IHttpPromise<T>;
}

然后,在您的控制器中,您只需使用新的接口。

代码语言:javascript
复制
constructor(private $http: IHttpServiceWithCustomConfig) {
    $http.get("/api/sessions/current", { avoidSudo: true }
}

您可以对IHttpInterceptor执行完全相同的操作

代码语言:javascript
复制
export interface IRequestConfigWithCustomConfig extends ng.IRequestConfig, IRequestShortcutConfigWithCustomConfig {

}

export interface IHttpInterceptorWithCustomConfig extends ng.IHttpInterceptor {
    request?: (config: IRequestConfigWithCustomConfig) => IRequestConfigWithCustomConfig | ng.IPromise<IRequestConfigWithCustomConfig>;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34178474

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档