【问题标题】:Angular 2 "No provider for String!"Angular 2“没有字符串的提供者!”
【发布时间】:2016-09-22 01:13:45
【问题描述】:

我正在尝试在 Angular 2 中创建通用数据服务,但遇到了一个奇怪的错误。本质上,我正在创建一个 HTTP 服务,其方法包含 api url 的一部分,以便我可以在多种情况下使用它。例如,我想传入 'projects/' 并将其与 'api/' 连接以获取 'api/projects/' ,然后我可以在 http 调用中使用它。

我当前的dataService.ts:

import { Injectable } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import 'rxjs/add/operator/map'
import { Observable } from 'rxjs/Observable';
import { Configuration } from '../app.constants';

@Injectable()
export class DataService {

    private actionUrl: string;
    private headers: Headers;

    constructor(private _http: Http, private _configuration: Configuration, public action: string) {

    this.actionUrl = _configuration.ApiUrl

    this.headers = new Headers();
    this.headers.append('Content-Type', 'application/json');
    this.headers.append('Accept', 'application/json');
    }

    public GetAll (action: string): Observable<any> {
        return this._http.get(this.actionUrl + action).map((response: Response) => <any>response.json());
    }

    public GetSingle (action: string, id: number): Observable<Response> {
        return this._http.get(this.actionUrl + action + id).map(res => res.json());
    }

    public Add (action: string, itemToAdd: any): Observable<Response> {
        var toAdd = JSON.stringify(itemToAdd);

        return this._http.post(this.actionUrl + action, toAdd, { headers: this.headers }).map(res => res.json());
    }

    public Update (action: string, id: number, itemToUpdate: any): Observable<Response> {
        return this._http
        .put(this.actionUrl + id, JSON.stringify(itemToUpdate), { headers: this.headers })
        .map(res => res.json());
    }

    public Delete (action: string, id: number): Observable<Response> {
        return this._http.delete(this.actionUrl + id);
    }
}

我尝试使用“项目”作为参数调用 GetAll 的组件来自:

import { Component, OnInit } from '@angular/core';
import { DataService } from '../services/dataService';

@Component({
    selector: 'project-detail',
    templateUrl: 'app/project/project-detail.component.html'
})
export class ProjectDetailComponent implements OnInit{
    projects: Object[];

    constructor(private _dataService: DataService) {}

    getProjects(): void {
        this._dataService.GetAll('projects').subscribe(projects => this.projects = projects);
    }
    ngOnInit(): void {
        this.getProjects();
    }
}

我确实在我的 app.module.ts 中将该服务添加为提供程序。还有一点需要注意的是,我这里展示的组件是一个名为 HomeComponent 的组件的子组件,它位于 AppComponent 中。

这就是 HomeComponent 的样子:

import { Component, OnInit } from '@angular/core';
import { ProjectDetailComponent } from '../project/project-detail.component';


@Component({
    selector: 'home',
    templateUrl: '<project-detail></project-detail>'
})

export class HomeComponent {}

错误:

EXCEPTION: Uncaught (in promise): Error: Error in      app/home/home.component.html:2:0 caused by: No provider for String!

我知道它在抱怨我传递给 GetCall 的字符串,但我就是不知道为什么。

任何帮助将不胜感激!

【问题讨论】:

  • 提供错误发生位置的代码 sn-p (app/home/home.component.html)

标签: angular angular2-services angular2-http angular2-di


【解决方案1】:

您不能随意注入任何东西。您尝试注入的任何内容都需要配置为可注入的。在大多数情况下,这意味着只需将类添加到providers 列表中。在字符串的情况下,它不是那么简单。我们需要做一些事情。

  1. 首先我们需要创建一个令牌1
  2. 然后使用该令牌配置要注入的字符串。
  3. 然后用同样的token,@Inject它进入目标。

import { OpaqueToken } from '@angular/core';

// 1. Create token
export const ACTION = new OpaqueToken('app.action');

// 2. Configure the `providers` (Maybe in the AppModule)
providers: [
  { provide: ACTION, useValue: 'the value you want'
]

import { Inject } from '@angular/core';

export class DataService {
  // 3. Injection target 
  constructor(@Inject(ACTION) action: string) {}
}

1 - 见Dependency Injection Tokens


更新

现在,对于 Angular 4,我们应该使用 InjectionToken 而不是 OpaqueToken

【讨论】:

  • 请原谅我的无知,因为我对 Angular2 / Typescript 很陌生,但是我将字符串传递给 GetAll 方法和他们做“this. heroService.create(name).then..."?似乎在整个教程中他们多次将字符串/整数/任何东西传递给服务方法,没有问题。
  • 没有错。这不是问题所在。它来自 DataService 的构造函数。 Angular 无法创建服务,因为它不知道从哪里获取字符串
  • 啊,我想我现在明白发生了什么事。谢谢!
  • @peeskillet 我试过这个,但不断收到Error: No provider for Token app.action! 错误。你知道我是否遗漏了这里没有提到的东西吗?谢谢。
猜你喜欢
  • 2017-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-14
  • 2016-12-20
  • 2015-07-26
  • 2018-01-09
  • 1970-01-01
相关资源
最近更新 更多