【问题标题】:Type is not assignable to type providedIn Property ProvidedIn is missing类型不可分配给类型 providedIn 缺少属性 ProvidedIn
【发布时间】:2019-06-04 08:45:44
【问题描述】:

我正在尝试在 Angular 的教程 https://angular.io/guide/http 的帮助下创建一个服务

我正在使用 Angular 7.0.7

服务会从一些 url 获取 json 数据:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable
export class ProductListService {
  constructor(private http: HttpClient) {
  }

  productListUrl: string = "https://blahblah.com/products";

  getProductList() {
    return this.http.get(this.productListUrl);
  }
}

我在@Injectable() 下得到一条带有此问题标题的波浪线。为什么会发生这种情况,我该如何解决?

我有一个将使用此服务的组件:

 import { ProductListService } from '../services/productList.service';
 @Component({
   selector: 'app-productlist',
   templateUrl: './productlist.component.html',
   styleUrls: ['./productlist.component.css'],
   providers: [ProductListService]
 })

【问题讨论】:

  • 您使用的是哪个角度版本?将括号添加到@Injectable()
  • 我使用的是 7.0.7
  • 天啊,非常感谢。我在上面的帖子中写了(),但忘记了代码。 Angular 在指出错误方面应该做得更好。

标签: angular typescript angular7


【解决方案1】:

你错过了为@Injectable()装饰器添加parenthesis

@Injectable()
export class ProductListService {
   constructor(private http: HttpClient) {
}

【讨论】:

    【解决方案2】:

    您的@Injectable 不正确。添加引用您将使用该服务的组件的providedIn 属性:

    @Injectable({
      providedIn: 'app-productlist',
    })
    export class ProductListService {
       constructor(private http: HttpClient) {
    }
    

    另一种解决方案是只使用这样的装饰器:@Injectable(),并在您的 app.module.ts 文件中将您的服务声明为提供者

    @Injectable()
    export class ProductListService {
       constructor(private http: HttpClient) {
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-22
      • 2017-12-05
      • 2018-07-06
      • 2021-10-04
      • 2018-11-11
      • 2019-02-04
      • 1970-01-01
      • 2017-06-28
      相关资源
      最近更新 更多