You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 7.0.7中@Injectable报错:缺失providedIn属性的解决咨询

Angular 7中@Injectable报错的原因与解决方法

嘿,我来帮你搞定这个Angular服务的报错问题!

错误原因

你遇到的这个报错,核心问题有两个:

  1. 语法错误:你的@Injectable后面没有加括号(),这不符合Angular装饰器的语法规范。
  2. 缺少必要配置:在Angular 6及以上版本(包括你用的7.0.7),@Injectable装饰器要求要么配置providedIn属性来指定服务的注入范围,要么在组件/模块的providers数组中注册该服务。你现在既没加括号,也没配置providedIn,所以才会触发“Property ProvidedIn is missing”的错误。

两种解决方法

方法1:使用providedIn: 'root'(官方推荐)

这是Angular 6+官方推崇的方式,能让服务成为根注入器的单例,还支持树摇优化(减少打包体积)。修改你的服务代码如下:

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

@Injectable({
  providedIn: 'root' // 配置根注入器提供服务
})
export class ProductListService {
  constructor(private http: HttpClient) { }
  productListUrl: string = "https://blahblah.com/products";
  getProductList() {
    return this.http.get(this.productListUrl);
  }
}

用这种方法的话,你可以把组件代码里的providers: [ProductListService]删掉,因为服务已经在根级别注册了,不用在组件里重复声明。

方法2:在组件providers中注册服务(适合多实例场景)

如果你需要每个组件实例都对应一个新的服务实例,可以保持组件的providers配置,同时修正服务的@Injectable语法:

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

@Injectable() // 只加括号,不需要providedIn
export class ProductListService {
  constructor(private http: HttpClient) { }
  productListUrl: string = "https://blahblah.com/products";
  getProductList() {
    return this.http.get(this.productListUrl);
  }
}

这种情况下,组件里的providers: [ProductListService]保留即可,每次创建组件实例时都会生成一个新的服务实例。

内容的提问来源于stack exchange,提问作者blue piranha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:35:36