0

问候,

当我遵循英雄之旅指南时,我想尝试一下有多个数据数组选项以及我使用哪些 herosUrl 从 InMemoryDbService 请求数据。我希望能够将 herosUrl 参数从英雄组件传递给英雄服务,以确定我想从数据库中获取哪一批英雄,但我在控制台中收到以下错误消息:

vendor.js:14812 ERROR Error: Uncaught (in promise): NullInjectorError: R3InjectorError(AppModule)[HeroService -> heroesUrl -> heroesUrl -> heroesUrl]: 
  NullInjectorError: No provider for heroesUrl!
NullInjectorError: R3InjectorError(AppModule)[HeroService -> heroesUrl -> heroesUrl -> heroesUrl]: 
  NullInjectorError: No provider for heroesUrl!
    at NullInjector.get (vendor.js:10919)
    at R3Injector.get (vendor.js:24642)
    at R3Injector.get (vendor.js:24642)
    at R3Injector.get (vendor.js:24642)
    at injectInjectorOnly (vendor.js:10774)
    at Module.ɵɵinject (vendor.js:10784)
    at Object.HeroService_Factory [as factory] (main.js:503)
    at R3Injector.hydrate (vendor.js:24869)
    at R3Injector.get (vendor.js:24630)
    at NgModuleRef$1.get (vendor.js:41631)
    at resolvePromise (polyfills.js:806)
    at resolvePromise (polyfills.js:765)
    at polyfills.js:867
    at ZoneDelegate.invokeTask (polyfills.js:413)
    at Object.onInvokeTask (vendor.js:46107)
    at ZoneDelegate.invokeTask (polyfills.js:412)
    at Zone.runTask (polyfills.js:181)
    at drainMicroTaskQueue (polyfills.js:583)

它说没有 heroUrl 的提供者,所以我怀疑我没有以正确的方式在组件中定义提供者:

import { Component, OnInit } from "@angular/core";

import { Hero } from "../hero";
import { HeroService } from "../hero.service";
import { MessageService } from "../message.service";

@Component({
  selector: "app-heroes",
  templateUrl: "./heroes.component.html",
  styleUrls: ["./heroes.component.scss"],
  providers: [{ provide: "heroesUrl", useValue: "heroesTwo" }]  //<-------------
})
export class HeroesComponent implements OnInit {
  heroes: Hero[];

  constructor(
    private heroService: HeroService,
    public messageService: MessageService
  ) {}

  ngOnInit(): void {
    this.heroService.getHeroes().subscribe(heroes => (this.heroes = heroes));
  }
}

这就是服务的样子,我尝试在其中注入参数:

import { Observable, of } from "rxjs";

import { HttpClient, HttpHeaders } from "@angular/common/http";
import { Injectable, Input, Inject, Optional } from "@angular/core";

import { Hero } from "./hero";
import { MessageService } from "./message.service";

import { catchError, map, tap } from "rxjs/operators";

@Injectable({
  providedIn: "root"
})
export class HeroService {
  constructor(
    private http: HttpClient,
    private messageService: MessageService,
    @Inject("heroesUrl") private heroesUrl: string //<-------------
  ) {}

  getHeroes(): Observable<Hero[]> {
    return this.http.get<Hero[]>(this.heroesUrl).pipe(
      tap(tappedData =>
        this.log("Fetched heroes: " + tappedData.map(data => data.name))
      ),
      catchError(this.handleError<Hero[]>("getHeroes", []))
    );
  }

  getHero(id: number): Observable<Hero> {
    const url = this.heroesUrl + "/" + id;
    return this.http.get<Hero>(url).pipe(
      tap(_ => this.log("fetched hero id=" + id)),
      catchError(this.handleError<Hero>("getHero id=" + id))
    );
  }

  private log(message: string) {
    this.messageService.add(`HeroService: ${message}`);
  }

  private handleError<T>(operation = "operation", result?: T) {
    return (error: any): Observable<T> => {
      console.error(error);
      this.log(`${operation} failed: ${error.body.error}`);
      return of(result as T);
    };
  }
}

在拦截http调用的服务中,实现InMemoryDbService:

return { heroesOne: heroes1, heroesTwo: heroes2 };

我一直在特别关注这些指南:

有人可以解释我做错了什么吗?

4

2 回答 2

1

将此行 -> providers: [{ provide: "heroesUrl", useValue: "heroesTwo" }] 添加到 Module.ts 文件提供程序数组而不是组件 ts 文件并尝试。

于 2020-03-04T13:02:09.350 回答
0

您需要在 app.module.ts 的提供者中声明您的 herosUrl,但随后每个英雄服务都将提供相同的 url。

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [
    HeroService,
    { provide: "heroesUrl", useValue: "heroesOne" }
  ],
  bootstrap: [AppComponent]
})

或者您也使用服务和 url 在组件中声明您的提供程序,然后每个组件都将拥有自己的服务和自己的 url。

@Component({
  selector: "app-heroes",
  templateUrl: "./heroes.component.html",
  styleUrls: ["./heroes.component.scss"],
  providers: [
    HeroService,
    { provide: "heroesUrl", useValue: "heroesTwo" }
  ]
})

并且您可以将两者结合起来,让通用 HeroesService 与“heroesOne” url 和其他 HeroesService 与其他特定组件的 url。

于 2020-03-04T13:31:37.993 回答