未捕获(承诺):错误:没有HttpService的提供者

时间:2017-06-25 09:02:45

标签: angular

我是角色4的新手,我真的很感激能帮到解决这个问题。

如果有app.module正在使用的core.module。 我正在尝试创建自己的HttpService以支持jwt并将其连接到模拟后端。

运行应用时,我收到此错误: 未捕获(承诺):错误:没有HttpService的提供者![enter image description here] 1

代码:

core.module.ts

import { MockBackend } from '@angular/http/testing';
import { fakeBackendFactory, fakeBackendProvider } from '../_mocks/fake-backend-provider';
import { JWTRequestOptions } from '../_models/jwtRequestOptions.model';
import { GuestOnlyGuard } from '../_guards/guest-only.guard';
import { NgModule, Optional, SkipSelf } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { HttpModule, Http, XHRBackend, ConnectionBackend, RequestOptions } from '@angular/http';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { TranslateModule } from '@ngx-translate/core';

import { ShellComponent } from '../shell/shell.component';
import { HeaderComponent } from '../shell/header/header.component';
import { AuthenticationService } from '../_services/authentication.service';
import { AuthenticationGuard } from '../_guards/authentication.guard';
import { I18nService } from '../_services/i18n.service';
import { HttpService } from '../_services/http.service';
import { HttpCacheService } from '../_services/http-cache.service';
import { CredantialsService } from "app/_services/credantials.service";
import { StorageService } from "app/_services/storage.service";
import { ValidatorsService } from "app/_services/validators.service";
import { FormValidatorsService } from "app/_services/form-validators.service";

export function createHttpService(backend: ConnectionBackend,
                                  jwtRequestOptions: JWTRequestOptions,
                                  httpCacheService: HttpCacheService,
                                  credantialsService: CredantialsService) {
  return new HttpService(backend, jwtRequestOptions, httpCacheService, credantialsService);
}

@NgModule({
  imports: [
    CommonModule,
    HttpModule,
    TranslateModule,
    RouterModule,
    NgbModule.forRoot()
  ],
  exports: [
    HeaderComponent
  ],
  declarations: [
    ShellComponent,
    HeaderComponent
  ],
  providers: [
    AuthenticationService,
    AuthenticationGuard,
    GuestOnlyGuard,
    I18nService,
    CredantialsService,
    HttpCacheService,
    StorageService,
    ValidatorsService,
    FormValidatorsService,
    MockBackend,
    fakeBackendProvider,
    {
      provide:Http,
      deps: [XHRBackend, RequestOptions, HttpCacheService, CredantialsService, StorageService],
      useFactory: createHttpService
    }
  ]
})
export class CoreModule {
  constructor(@Optional() @SkipSelf() parentModule: CoreModule) {
    // Import guard
    if (parentModule) {
      throw new Error(`${parentModule} has already been loaded. Import Core module in the AppModule only.`);
    }
  }
}

Http.service.ts

import 'rxjs/add/operator/do';
import 'rxjs/add/observable/throw';
import { requireProjectModule } from '@angular/cli/utilities/require-project-module';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Subscriber } from 'rxjs/Subscriber';
import { extend } from 'lodash';
import { environment } from 'environments/environment';
import { Logger } from 'app/_services/logger.service';
import { HttpCacheService } from './http-cache.service';
import { HttpCachePolicy } from 'app/_models/request-options-args.model';
import { CredantialsService } from "app/_services/credantials.service";
import {
  Http,
  ConnectionBackend,
  RequestOptions,
  Request,
  Response,
  RequestOptionsArgs,
  RequestMethod,
  ResponseOptions
} from '@angular/http';
import { JWTRequestOptions } from "app/_models/jwtRequestOptions.model";

const log = new Logger('HttpService');
const newTokenKey = "newToken";

@Injectable()
export class HttpService extends Http {

  constructor(backend: ConnectionBackend,
              private defaultOptions: JWTRequestOptions,
              private httpCacheService: HttpCacheService,
              private credantials: CredantialsService) {
    super(backend, defaultOptions);
  }

  get(url: string, options?: RequestOptionsArgs): Observable<Response> {
    return this.request(url, extend({}, options, { method: RequestMethod.Get }));
  }

  post(url: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
    return this.request(url, extend({}, options, {
      body: body,
      method: RequestMethod.Post
    }));
  }

  put(url: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
    return this.request(url, extend({}, options, {
      body: body,
      method: RequestMethod.Put
    }));
  }

  delete(url: string, options?: RequestOptionsArgs): Observable<Response> {
    return this.request(url, extend({}, options, { method: RequestMethod.Delete }));
  }

  patch(url: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
    return this.request(url, extend({}, options, {
      body: body,
      method: RequestMethod.Patch
    }));
  }

  head(url: string, options?: RequestOptionsArgs): Observable<Response> {
    return this.request(url, extend({}, options, { method: RequestMethod.Head }));
  }

  options(url: string, options?: RequestOptionsArgs): Observable<Response> {
    return this.request(url, extend({}, options, { method: RequestMethod.Options }));
  }

  request(request: string|Request, options?: RequestOptionsArgs): Observable<Response> {
    options = options || {};
    let url: string;

    if (typeof request === 'string') {
      url = request;
      request = environment.serverUrl + url;
    } else {
      url = request.url;
      request.url = environment.serverUrl + url;
    }

    if (options.cache == false ) {
      return this.httpRequest(request, options);
    }
    
    return this.tryFromCacheAndCacheResult(request, url, options);
  }
  
  private tryFromCacheAndCacheResult(request: string|Request, url: string, options?: RequestOptionsArgs):Observable<Response> {
    return new Observable((subscriber: Subscriber<Response>) => {
        const cachedData = options.cache === HttpCachePolicy.Update ? null : this.httpCacheService.getCacheData(url);
        if (cachedData !== null) {
          subscriber.next(new Response(cachedData));
          subscriber.complete();
          return 
        }
        
        this.httpRequest(request, options).subscribe(
            (response: Response) => {
              this.httpCacheService.setCacheData(url, null, new ResponseOptions({
                body: response.text(),
                status: response.status,
                headers: response.headers,
                statusText: response.statusText,
                type: response.type,
                url: response.url
              }));
              subscriber.next(response);
            },
            (error) => subscriber.error(error),
            () => subscriber.complete()
          );
      });
  }
  // Customize the default behavior for all http requests here if needed
  private httpRequest(request: string|Request, options: RequestOptionsArgs): Observable<Response> {
    let req = super.request(request, options);
    if (!options.skipErrorHandler) {
      req = req.catch(this.errorHandler.bind(this));
    }
    return req;
  }

  // Customize the default error handler here if needed
  private errorHandler(response: Response): Observable<Response> {
    if (environment.production) {
      // Avoid unchaught exceptions on production
      log.error('Request error', response);
      return Observable.throw(response);
    }
    throw response;
  }
 
}

import { BaseRequestOptions } from '@angular/http';

export class JWTRequestOptions extends BaseRequestOptions {
    public token: string;
    constructor (customOptions?: any) {
  
    super();
        let user = JSON.parse(localStorage.getItem('user'));
        this.token = user && user.token;
        this.headers.append('Content-Type', 'application/json');
        this.headers.append('Authorization', 'Bearer ' + this.token );        
    }
}

App.module

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { TranslateModule } from '@ngx-translate/core';

import { AppComponent } from './app.component';
import { AppRoutingModule } from 'app/_modules/app-routing.module';

import { CoreModule } from 'app/_modules/core.module';
import { SharedModule } from 'app/_modules/shared.module';
import { HomeModule } from 'app/_modules/home.module';
import { AboutModule } from 'app/_modules/about.module';
import { LoginModule } from 'app/_modules/login.module';
import { RegistrationComponent } from './registration/registration.component';
import { RouterModule } from '@angular/router';
import { RegistrationService } from "app/_services/registration.service";
import { ForgetPasswordComponent } from './forget-password/forget-password.component';
import { PasswordRecoveryService } from "app/_services/password-recovery.service";

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    TranslateModule.forRoot(),
    NgbModule.forRoot(),
    CoreModule,
    SharedModule,
    HomeModule,
    AboutModule,
    LoginModule,
    AppRoutingModule,
    RouterModule,
    ReactiveFormsModule
  ],
  declarations: [AppComponent, RegistrationComponent, ForgetPasswordComponent],
  providers: [RegistrationService, PasswordRecoveryService],
  bootstrap: [AppComponent]
})
export class AppModule { }

任何帮助都将得到帮助。

0 个答案:

没有答案