在Angular中,如果意外地得到了一个令牌错误,可能是由于以下几种情况引起的:
示例代码:
import { Injectable } from '@angular/core';
@Injectable()
export class MyService {
  constructor() { }
}
@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.css']
})
export class MyComponent {
  constructor(private myService: MyService) { }
}
在上面的代码中,MyComponent 使用 MyService 进行依赖注入。确保 MyService 在正确的模块中导入并在 providers 数组中提供。
示例代码:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
@NgModule({
  imports: [
    BrowserModule,
    // Other modules
  ],
  declarations: [
    // Components
  ],
  providers: [
    // Services
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }
在上面的代码中,确保正确导入了 BrowserModule 和其他所需的模块。
示例代码:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { MyService } from './my-service';
@NgModule({
  imports: [
    BrowserModule,
    // Other modules
  ],
  declarations: [
    // Components
  ],
  providers: [
    MyService, // Only provide once
    // Other services
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }
在上面的代码中,确保只在 providers 数组中提供了 MyService 一次。
通过检查以上几种情况,您应该能够解决Angular中意外的令牌错误。