我在使用Angular 4.3.2中的其他服务时遇到问题。当试图使用' http'在LoggerService中我收到以下错误:无法读取属性' post'未定义的。似乎Http服务没有正确注入,因为它正在另一个服务中使用。如果我直接从组件调用日志函数,它会按预期工作。
app.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HttpModule } from '@angular/http';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { AppComponent } from './app.component';
import { HomeComponent } from '../home/home.component';
import { CustomerDataLookupComponent } from '../customerdatalookup/customer-data-lookup.component';
import { AppRoutingModule } from './app.routing.module';
import { LoggerService } from './services/logger.service';
@NgModule({
declarations: [
AppComponent,
HomeComponent,
CustomerDataLookupComponent
],
imports: [
// Custom
AppRoutingModule,
// Angular
CommonModule,
HttpModule,
BrowserAnimationsModule
],
providers: [
LoggerService,
CustomerDataLookupRestService
],
bootstrap: [AppComponent]
})
export class AppModule { }
客户数据查对rest.service.ts
import { CustomerDataLookupRestServiceInterface } from '../model/customer-
data-lookup-rest.interface';
import { Observable } from 'rxjs/Rx';
import { CustomerDataLookup } from '../model/customer-data-lookup';
import { RestResponse } from '../../app/model/rest-response';
import { Http } from '@angular/http';
import { environment } from '../../environments/environment';
import { LoggerService } from '../../app/services/logger.service';
import { Injectable } from '@angular/core';
@Injectable()
export class CustomerDataLookupRestService implements CustomerDataLookupRestServiceInterface {
constructor(private http: Http, private loggerService: LoggerService) { }
updateCustomerDataLookup(customerDataLookup: CustomerDataLookup): Observable<RestResponse> {
return this.http
.put(`${environment.configurationRestApiUrl}/CustomerDataLookup/${customerDataLookup.id}`, JSON.stringify(customerDataLookup))
.map(response => response.json() as RestResponse)
.catch(this.loggerService.handleError);
}
logger.service.ts
import { Log } from '../model/log';
import { Http } from '@angular/http';
import { BaseResult } from '../model/base-result';
import { environment } from '../../environments/environment';
import { Observable } from 'rxjs/Rx';
import { Injectable } from '@angular/core';
@Injectable()
export class LoggerService {
constructor(private http: Http) { }
log(log: Log): Observable<BaseResult> {
return this.http.post(`${environment.restApiUrl}/Log/`, JSON.stringify(log))
.map(response => response.json() as BaseResult);
}
handleError(error: Response): Observable<string> {
const errorMessage = 'TEST';
const log = new Log('ERROR', errorMessage);
this.http.post(`${environment.configurationRestApiUrl}/Log/`, JSON.stringify(log))
.map(response => response.json() as BaseResult);
return Observable.throw(errorMessage);
}
}
答案 0 :(得分:0)
该决议与A. Tim建议的那样。
用.catch(this.loggerService.handleError);
替换.catch((error) => this.loggerService.handleError(error));
后,一切按预期工作。