установить токен заголовкам в угловых - PullRequest
0 голосов
/ 11 февраля 2019

Я добавляю перехватчики в мой угловой проект, но они не работают и не запускаются.Я вставляю токен в заголовки, но ответом является ошибка со статусом

401 (not authenticated)

Я внедряю перехватчики в поставщиках таблиц в файле app.module.ts, но он также не работает.

код перехватчиков:

import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpErrorResponse } from '@angular/common/http';
import { Injectable, Injector } from '@angular/core';
import { Observable } from 'rxjs';
import {Router} from '@angular/router';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

  constructor(public router:Router) {console.log('here'); }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

   const authToken = localStorage.getItem('token');
   console.log(authToken);
   const clonedRequest = req.clone({
            headers: req.headers.set('Content-Type', 'application/json')
            .set('Authorization', 'Bearer '+authToken)

        });

    return next.handle(clonedRequest);
  }
}

код app.module, где я внедряю перехватчики:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { PLATFORM_ID, APP_ID, Inject } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header.component';
import { FooterComponent } from './footer/footer.component';
import { LoginComponent } from './login/login.component';
import { RegisterComponent } from './register/register.component';
import { HomeComponent } from './home/home.component';
import { ProfileComponent } from './profile/profile.component';
import { AboutComponent } from './about/about.component';
import { ServicesComponent } from './services/services.component';
import { AuthInterceptor } from './services/auth.interceptor';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { ContactComponent } from './contact/contact.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { ToastrModule } from 'ng6-toastr-notifications';
import { FileUploadComponent } from './file-upload/file-upload.component';
@NgModule({
    declarations: [
      AppComponent,
      HeaderComponent,
      FooterComponent,
      LoginComponent,
      RegisterComponent,
      HomeComponent,
      ProfileComponent,
      AboutComponent,
      ServicesComponent,
      ContactComponent,
      FileUploadComponent
    ],
    imports: [
      BrowserModule,
      AppRoutingModule,
      HttpModule,
      HttpClientModule,
      FormsModule,
      BrowserAnimationsModule,
      ToastrModule.forRoot(),
    ],
    providers: [
      AuthInterceptor,
      {
        provide: HTTP_INTERCEPTORS,
        useClass: AuthInterceptor,
        multi: true
      }
    ],
    bootstrap: [AppComponent]
})
export class AppModule {
    constructor(
      @Inject(PLATFORM_ID) private platformId: Object,
      @Inject(APP_ID) private appId: string) {
      const platform = isPlatformBrowser(platformId) ?
        'in the browser' : 'on the server';
      console.log(`Running ${platform} with appId=${appId}`);
    }
}

Ответы [ 2 ]

0 голосов
/ 11 февраля 2019

@ dev_2019 попробуйте это один раз.установите заголовки, как показано ниже

   intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

   const authToken = localStorage.getItem('token');
   const clonedRequest = req.clone({
        headers: new HttpHeaders({
          Authorization: authToken,
          "Content-Type": "application/json"
        })
      });
   return next.handle(clonedRequest);

, и, как сказал @Ramesh, обновите провайдеров app.module с помощью

providers: [  {provide: HTTP_INTERCEPTORS,useClass: AuthInterceptor ,multi:true }  ]
0 голосов
/ 11 февраля 2019

Выполните синтаксический анализ вашего токена следующим образом.

    const authToken = JSON.parse(localStorage.getItem('token'));

    req = req.clone({
      setHeaders: {
        Authorization: `Bearer ${token.token}`, // Or whatever the property you have, if any.
        'Content-Type': 'application/json'
      }
     });

    return next.handle(req);

Это означает, что запрос не влияет на привлечение перехватчика. Измените свой раздел обеспечения следующим образом.

providers: [
    { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }
],
...