@Injectable在工作时@Inject不起作用



我遇到了奇怪的问题。

我得到了非常简单的服务:

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工作时不起作用?

同样的情况。当我将项目从Angular 5迁移到7版本时。对我的作品:

添加到 tsconfig.json - " emitdecoratormetadata":true

完整的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": []
  }
}

请检查您的@NgModule声明,也许您从imports列表中错过了HttpClientModule

如果我正确理解,则应添加Reflect-Metadata库。https://www.typescriptlang.org/docs/handbook/decorators.html#metadata

最新更新