11

我正在为 rc5 的 angular2-jwt 文档苦苦挣扎

这是我的 NgModule

import { AuthHttp } from 'angular2-jwt';



 @NgModule({
  imports: [ BrowserModule, 
             routing,
             HttpModule,
             FormsModule,

            ],
  declarations: [ 
                  AppComponent,
                  LoginComponent, 
                  NavbarComponent,
                  DashboardComponent,
                  ModelsComponent
                ],
  providers: [AuthGuard,
              ModelService,
              AuthHttp
              ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }

这是我的服务

import { Injectable } from '@angular/core';
import {Http} from '@angular/http';
import 'rxjs/add/operator/map';
import { Model } from './model';
import { AuthHttp } from 'angular2-jwt';
import {Observable} from "rxjs/Rx";

@Injectable()
export class ModelService {
  private _url = "http://127.0.0.1:8050/test/model";

  constructor(private _http: Http,private _authHttp: AuthHttp){
    //this.jwt = localStorage.getItem('id_token');
  }


  getPollModles(){
    return Observable.interval(5000).switchMap(() => this._authHttp.get(this._url)).map(res => res.json());
  }

}

如何让 angular2_jwt 与 rc5 一起使用?

当我将服务添加到构造函数时,我得到以下错误。

constructor(private route: ActivatedRoute,
                public router: Router,
                private modelService: ModelService) 

core.umd.js:5995EXCEPTION: Uncaught (in promise): Error: Error in ./ModelsComponent class ModelsComponent_Host - inline template:0:0 caused by: No provider for AuthConfig!
4

4 回答 4

18

app.module 像这样导入:

import { AuthHttp, AuthConfig, AUTH_PROVIDERS, provideAuth } from 'angular2-jwt';

并添加提供者:

providers: [        
        AuthHttp,
        provideAuth({
            headerName: 'Authorization',
            headerPrefix: 'bearer',
            tokenName: 'token',
            tokenGetter: (() => localStorage.getItem('id_token')),
            globalHeaders: [{ 'Content-Type': 'application/json' }],
            noJwtError: true
        })
    ],
于 2016-09-02T14:55:19.310 回答
0

如果提供程序的顺序错误,也会发生此错误:

providers: [
  provideAuth({
    headerName: 'Authorization',
    headerPrefix: 'my-bearer-prefix',
    tokenName: 'my-token-name',
    tokenGetter: (() => localStorage.getItem('token')),
    globalHeaders: [{ 'Content-Type': 'application/json' }],
    noJwtError: true
  }),
  AuthHttp
]

导致 Angular 2.0.0 和 angular2-jwt 0.1.23 出现错误。

于 2016-09-27T09:05:42.443 回答
0

您必须在NgModule. 添加AuthConfig到您@NgModule的声明中。

编辑:这可能是胡说八道。

你更新angular2-jwt到当前版本了吗?

于 2016-09-02T14:13:04.293 回答
0

尝试这个: ...

 imports: [ AuthModule.forRoot(new AuthConfig({
  headerName: 'Authorization',
  headerPrefix: 'my-bearer-prefix',
  tokenName: 'my-token-name',
  tokenGetter: (() => localStorage.getItem('token') || ''),
  globalHeaders: [{ 'Content-Type': 'application/json' }],
  noJwtError: true
}))]
于 2018-01-12T22:39:58.150 回答