我遇到了一个奇怪的问题。
我的服务非常简单:
import { Inject, Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class EchoService {
constructor(private httpClient: HttpClient) {}
public makeCall(): Observable<any> {
return this.httpClient.get<any>('https://jsonplaceholder.typicode.com/posts/1');
}
}
现在我正在尝试在我的组件中重用它:
import { Component, Inject, OnInit } from '@angular/core';
import { EchoService } from './services/echo.service';
import { Observable } from 'rxjs/Observable';
@Component({
selector: 'my-app',
templateUrl: `app.component.html`,
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
public response: Observable<any>;
constructor(private echoService: EchoService) {}
public ngOnInit(): void {
this.response = this.echoService.makeCall();
}
}
而且......我遇到了Uncaught Error: Can't resolve all parameters for EchoService: (?).
当我从@Injectable
切换到@Inject
时,一切正常:
constructor(@Inject(HttpClient) private httpClient: HttpClient) {}
并在组件中:
constructor(@Inject(EchoService) private echoService: EchoService) {}
我的tsconfig.json
是:
{
"compilerOptions": {
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": [ "dom", "esnext" ]
}
}
情况如何?为什么@Injectable
不起作用,而@Inject
有效?
答案 0 :(得分:0)
请检查您的@NgModule
声明,否则可能会错过HttpClientModule
列表中的imports
。
答案 1 :(得分:0)
如果我理解正确,您应该添加reflect-metadata库。 https://www.typescriptlang.org/docs/handbook/decorators.html#metadata
答案 2 :(得分:0)
同样的情况。当我将项目从Angular 5迁移到7版本时。对我来说有用:
添加到 tsconfig.json -“ emitDecoratorMetadata”:是
完整的tsconfig.json:
{
"compilerOptions": {
"baseUrl": "./src",
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"sourceMap": true,
"moduleResolution": "node",
"target": "es2015",
"rootDir": "./src",
"typeRoots": [
"node_modules/@types"
],
"lib": [
"es2018",
"dom"
],
"skipLibCheck": true,
"types": []
}
}