当我使用 Injector.get() 时,一个服务会引发异常



我有一个发出http请求的服务。让我们考虑一种方法:

export class JsonApiService {
constructor(private http: Http, private localStorageService: LocalStorageService) { }
public get(url, params?, requestOptions: any = {}): Observable<any> {        
const options = this.buildRequestOptions(requestOptions);
const fullUrl = this.buildUrl(url);
const urlWithQuery = this.addQueryParams(fullUrl, params);
return this.http.get(urlWithQuery, options)         
.map(this.extractData)
.catch((e) => this.handleError(e));
}
}

正如 yoy 所看到的,我使用 catch 来缓存错误。这是handleError函数:

private handleError(error: any): Observable<any> {
let body  = error.json ? error.json() : '';
if (!environment.production) {
console.warn(error);
}
this.onError.next(body);       
if(error.status === 0) {
body.message = 'Can't connect to the server.';
}
return Observable.throw(body);
}

此任务的非常标准代码。现在,我需要处理一个特定的服务器错误响应。特定错误 json 包含一个字段checkIntegration。所以,我想检查错误以及它是否包含此字段。如果是,则执行一些自定义逻辑。我不想把这个逻辑放在JsonApiService本身,因为我想从一个项目到另一个项目重用这个服务,而且我实际上确实这样做了.我一直在最近的 3 个项目中使用它,没有任何修改。

因此,我编写了自定义错误处理程序:

export class ErrorHandlerService extends ErrorHandler {
constructor(private injector: Injector) {
super(true);
let jsonApiService = this.injector.get(JsonApiService);
jsonApiService.onError.subscribe((err) => {
this.handleError(err);
})
}
...
}

如您所见,我使用onError.只是Subject. 但是,我在应用程序启动时出错:Cannot read property 'notifyOptions' of undefined ; Zone: <root> ; Task: Promise.then ; Value: TypeError: Cannot read property 'notifyOptions' of undefined at new LocalStorageService (local-storage.service.js:34)

错误抛出在local-storage.service中。这不是我的服务,但我将此服务注入JsonApiService.我相信当我在处理程序中使用注入器时,并非所有服务都是创建的。有什么想法吗?

附言。我使用以下库进行本地存储: https://github.com/phenomnomnominal/angular-2-local-storage/blob/master/src/local-storage.service.ts#L38

在上面的代码中,LocalStorageService可能没有正确配置,因为所述属性源自配置提供程序。

该错误在实例化JsonApiService引发,它将阻止提供程序正常运行。用onError处理错误是没有意义的,因为错误早在handleError之前就抛出了。

它应该在实例化问题提供程序的位置捕获:

export class JsonApiService {
private localStorageService?: LocalStorageService;
constructor(private http: Http, private injector: Injector) { }
try {
this.localStorageService = injector.get(LocalStorageService);
} catch (err) {
...
}

但正确的解决方案是首先解决问题的原因。

相关内容

最新更新