没有为字符串提供程序

没有为字符串提供程序

本文介绍了Angular 2“没有为字符串提供程序!";的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to create a generalized data service in Angular 2, and I'm encountering a strange error. Essentially, I'm creating an HTTP service whose methods take in part of the api url so that I can use it for multiple cases. For example, I would like to pass in 'projects/' and join it with 'api/' to get 'api/projects/' which I could then use in the http calls.

我当前的dataService.ts:

My current 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的组件:

The component I'm trying to call GetAll with 'projects' as a parameter from:

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中将服务添加为提供者.还有一点需要注意的是,我在这里显示的组件是位于AppComponent中的名为HomeComponent的组件的子组件.

I do have the service added as a provider in my app.module.ts. One more thing of note is that the component I show here is a child component of a component called HomeComponent, which sits in AppComponent.

这是HomeComponent的样子:

This is what HomeComponent looks like:

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的字符串,但我只是不知道为什么.

I know that it's complaining about the string I'm passing into GetCall, but I just don't know why.

任何帮助将不胜感激!

推荐答案

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

You can't just inject arbitrary things. Anything you try to inject, needs to be configured to be injectable. In most cases that means just adding the class to the providers list. In the case of a string, it's not that simple. We need to do a few things.

  1. 首先我们需要创建一个令牌
  2. 然后使用该令牌配置要注入的字符串.
  3. 然后使用相同的令牌,将其@Inject插入目标.
  1. First we need to create a token
  2. Then configure the string to be injected, using that token.
  3. Then with the same token, @Inject it into the target.


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) {}
}



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

Now, with Angular 4, we should use InjectionToken rather than OpaqueToken

这篇关于Angular 2“没有为字符串提供程序!";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 01:26