NativeScript中的httpinterceptor无法正常工作

时间:2019-05-12 06:52:04

标签: angular nativescript nativescript-angular

我正在使用httpinterceptor拦截具有JWT令牌的http标头,但无法正常工作。

这是我的GET方法。可以在请求中手动添加标头,但可以使用httpinterceptor。

loadLoginData() {
        const url = 'http://mywebpage/myurl',
        const tokenInfo = appSettings.getString('TokenInfo');
        request({
            url: url,
            method: "GET",
            headers: { Authorization: `Bearer ${tokenInfo}`, "Content-Type": "application/json" },
        }).then((response: HttpResponse) => {
            const d = response.content.toJSON();
        }, (e) => {
            alert(e);
        });
    }

headers: { Authorization:承载者$ {tokenInfo} , "Content-Type": "application/json" },->如果添加此行,则效果很好,否则请求将变为匿名。

httpinterceptors.ts

import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable } from 'rxjs';
import * as appSettings from "tns-core-modules/application-settings";

@Injectable({
  providedIn: 'root'
})

export class httpInterceptor implements HttpInterceptor {
  intercept(request: HttpRequest<any>, newRequest: HttpHandler): Observable<HttpEvent<any>> {
    const tokenInfo = appSettings.getString('TokenInfo');
    if (tokenInfo) {
      request = request.clone({
        setHeaders: {
          Authorization: `Bearer ${tokenInfo}`,
          'Content-Type': 'application/json'
        }
      });
    }

    return newRequest.handle(request);
  }
}

shared.moduele.ts

import { NgModule, NO_ERRORS_SCHEMA } from '@angular/core';
import { NativeScriptCommonModule } from 'nativescript-angular/common';
import { NativeScriptFormsModule } from 'nativescript-angular/forms';
import { RouterModule } from '@angular/router';
import { ReactiveFormsModule, FormsModule } from '@angular/forms';
import { NativeScriptHttpModule } from "nativescript-angular/http";
import { NativeScriptRouterModule } from "nativescript-angular/router";
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { httpInterceptor } from '../interceptor/httpInterceptor';

@NgModule({
  declarations: [],
  imports: [
    NativeScriptCommonModule,
    NativeScriptFormsModule,
    FormsModule,
    ReactiveFormsModule,
    RouterModule,
    NativeScriptHttpModule,
    NativeScriptRouterModule
  ],
  exports: [
    NativeScriptCommonModule,
    NativeScriptFormsModule,
    FormsModule,
    ReactiveFormsModule,
    RouterModule,
    NativeScriptHttpModule,
    NativeScriptRouterModule
  ],
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: httpInterceptor, multi: true }
  ],
  schemas: [NO_ERRORS_SCHEMA]
})
export class SharedModule { }

我在这里犯了什么错误?

1 个答案:

答案 0 :(得分:0)

您正在混合{N} Core和Angular。 "tns-core-modules/http"模块通常在具有JavaScript / TypeScript的{N}核心应用程序上使用。

对于Angular,您应该参考HttpClientModule,拦截器将侦听和拦截仅通过Angular的HttpClient类发出的调用。