angular - 在 Angular 4 中使用 ngx-restangular 在 Http 请求中添加自定义 header

标签 angular typescript restangular angular-http

我正在使用 ngx-restangular对于 Angular 4 中的 http 请求。我必须在某些事件中设置自定义 header ,从用户那里获取一些输入,然后创建 token ,将其传递给 中的 Requestheader API

这是我用来设置自定义 header 的代码。

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { RestangularModule, Restangular, RestangularHttp } from 'ngx-restangular';
import { RestangularConfigFactory } from '../app.module';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from '../app.component';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Http, Headers, Response, RequestOptions,  } from '@angular/http';


@Component({
    templateUrl: 'login.component.html'
})

export class LoginComponent implements OnInit {
    model: any = {};
    loading = false;
    returnUrl: string;
    headers: Headers;
    options: RequestOptions;

    constructor(
        private route: ActivatedRoute,
        private router: Router,
        private restangular: Restangular) { }

    ngOnInit() {
        // reset login status
        // get return url from route parameters or default to '/'
        this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
    }

    login() {
        this.loading = true;
        this.headers = new Headers();
        this.headers.append('Content-Type', 'application/json');
        this.headers.append('Authorization', 'Basic ' + btoa(this.model.username + ':' + this.model.password));
        this.options = new RequestOptions({ headers: this.headers });
        console.log(this.options);
        this.restangular.one('authentication').one('user').get([''], [this.headers]).subscribe( response => {
            console.log(response);
          });
    }
}

现在使用它我得到输出 ActualImage 我需要这样的东西 DesiredImage

在下面的 desired image 图像中,您可以在 Request Header 中看到一个名为 authorization 的新字段,这是我想要实现的使用 ngx-restangular

感谢任何帮助。

最佳答案

使用拦截器=>

RestangularProvider.addFullRequestInterceptor((element, operation, path, url, 
headers, params)=> {
   return {
     params: Object.assign({}, params, {sort:"name"}),
     headers: headers,
     element: element
   }
 });

https://github.com/2muchcoffeecom/ngx-restangular#addfullrequestinterceptor

关于angular - 在 Angular 4 中使用 ngx-restangular 在 Http 请求中添加自定义 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49276627/

相关文章:

angular - npm run 不通过 --configuration 来构建任务

angular - Sass math.div 函数在 angular 应用程序中未定义,但在 angular lib 中定义

angularjs - 登录后设置 RestAngular 默认请求参数

angularjs - 无法访问矩形请求之外的范围变量

angular - 如何在 Angular 6 中用 spy 对象替换组件范围的服务?

javascript - 转换 RxJS Observable

typescript - 如何在 typescript 中设置 redux reducer 的初始状态?

javascript - 在 typescript 的同一行导入和调用函数

typescript - 如何防止 TypeScript 中断基于 Webpack 的 ProvidePlugin 上声明的未解析变量的 Webpack 构建?

javascript - 强制 DOM 在更改对工厂模型的 $scope 模型引用时进行渲染