简体   繁体   English

错误:未捕获(承诺):错误:没有服务提供程序-Angular 4.1.2

[英]Error: Uncaught (in promise): Error: No provider for Service - Angular 4.1.2

Im pretty new in Angular, and i'm having annoying problem which i dont understand. 我是Angular的新人,我遇到了我不理解的烦人的问题。 I want to inject my service to @NgModule so that i can use it anywhere in application without needing to declare or import it again. 我想将我的服务注入@NgModule,以便我可以在应用程序中的任何位置使用它,而无需再次声明或导入它。 Then when i run my project everything is fine after refresh page and get this exception: 然后,当我运行我的项目时,刷新页面后一切都很好,并得到以下异常:

Error: Uncaught (in promise): Error: No provider for Service 错误:未捕获(承诺):错误:没有服务提供者

make.service.ts make.service.ts

import { Injectable, Inject } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class MakeService {
    originUrl;
    constructor(private http: Http, @Inject('ORIGIN_URL') originUrl: string) {
        this.originUrl = originUrl;
    }

    getMakes() {
        return this.http.get(this.originUrl + '/api/makes')
            .map(res => res.json());
    }

    getFeatures() {
        return this.http.get(this.originUrl + '/api/features')
            .map(res => res.json());
    }

}

This service im declaring in app.module.ts : 该服务在app.module.ts中声明:

import { MakeService } from './services/make.service';
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { sharedConfig } from './app.module.shared';


@NgModule({
    imports: [
        BrowserModule,
        FormsModule,
        HttpModule,
        ...sharedConfig.imports
    ],
    declarations: sharedConfig.declarations,
    bootstrap: sharedConfig.bootstrap,
    providers: [MakeService, { provide: 'ORIGIN_URL', useValue: location.origin }]
})
export class AppModule {
}

And finally use it in my component vehicle-form.component.ts 最后在我的组件vehicle-form.component.ts中使用它

import { Component, OnInit } from '@angular/core';
import { MakeService } from '../../services/make.service';

@Component({
  selector: 'app-vehicle-form',
  templateUrl: './vehicle-form.component.html',
  styleUrls: ['./vehicle-form.component.css'],
})
export class VehicleFormComponent implements OnInit {
    makes;
    vehicle = {};
    constructor(private makeService: MakeService) { }

  ngOnInit() {
      this.makeService.getMakes().subscribe(makes => {
          this.makes = makes
          console.log("MAKES", this.makes);
      });
  }

  onMakeChange() {
      console.log("VEHICLE", this.vehicle);
  }

}

When im declaring provider in my component like this: 当在我的组件中声明提供程序时,如下所示:

...
@Component({
  selector: 'app-vehicle-form',
  templateUrl: './vehicle-form.component.html',
  styleUrls: ['./vehicle-form.component.css'],
  providers: [MakeService]
})
...

Then everything is working but thats not what i want to archive. 然后一切正常,但这不是我要存档的内容。

@Maximus yes i'm using routing. @Maximus是的,我正在使用路由。 I dont know why angular CLI generated 3 separated files instead one. 我不知道为什么有角度的CLI会生成3个分离的文件而不是一个。

Soo those three files are: app.module.server.ts, app.module.shared.ts, app.module.client.ts 所以这三个文件是:app.module.server.ts,app.module.shared.ts,app.module.client.ts

I had to rename app.module.client to app.module.ts to generate component from CLI becouse there was error that app.module file is missing. 我必须将app.module.client重命名为app.module.ts才能从CLI生成组件,因为缺少app.module文件的错误。

Soo i think the app.module.client is now old app.module file which imports the 2 other files app.module.server and app.module.shared. 所以我认为app.module.client现在是旧的app.module文件,它导入了另外两个文件app.module.server和app.module.shared。

The app.module.shared file look like: app.module.shared文件如下所示:

import { FormsModule } from '@angular/forms';
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';

import { AppComponent } from './components/app/app.component';
import { NavMenuComponent } from './components/navmenu/navmenu.component';
import { HomeComponent } from './components/home/home.component';
import { FetchDataComponent } from './components/fetchdata/fetchdata.component';
import { CounterComponent } from './components/counter/counter.component';
import { VehicleFormComponent } from './components/vehicle-form/vehicle-form.component';

export const sharedConfig: NgModule = {
    bootstrap: [ AppComponent ],
    declarations: [
        AppComponent,
        NavMenuComponent,
        CounterComponent,
        FetchDataComponent,
        HomeComponent,
        VehicleFormComponent
    ],
    imports: [
        FormsModule,
        RouterModule.forRoot([
            { path: '', redirectTo: 'home', pathMatch: 'full' },
            { path: 'vehicles/new', component: VehicleFormComponent },
            { path: 'home', component: HomeComponent },
            { path: 'counter', component: CounterComponent },
            { path: 'fetch-data', component: FetchDataComponent },
            { path: '**', redirectTo: 'home' }
        ])
    ]
};

I think you are tilting at windmills. 我想你在风车上倾斜。 I would better export your constant as static field in some class: 我最好在某些类中将常量导出为静态字段:

some.settings.ts some.settings.ts

export class SomeSettings {
   public static ORIGIN_URL=window.location.origin;
}

And then use it in make.service.ts 然后在make.service.ts中使用它

import { Injectable, Inject } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class MakeService {
    constructor(private http: Http) { 
        const settings = require( './some.settings' );
        this.SomeSettings = settings.SomeSettings;
    }
    SomeSettings: any;

    getMakes() {
        return this.http.get(SomeSettings.ORIGIN_URL + '/api/makes')
            .map(res => res.json());
    }

    getFeatures() {
        return this.http.get(SomeSettings.ORIGIN_URL + '/api/features')
            .map(res => res.json());
    }
}

I am also seeing the same problem with you. 我也看到您遇到同样的问题。 But when I put the provider declaration (dependency injection) inside app.component.ts, which is my root component, the issue is not seen with me anymore. 但是,当我将提供程序声明(依赖注入)放在我的根组件app.component.ts中时,这个问题就再也看不到了。

Best, 最好,

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Angular 2 No Provider或DI错误(未捕获(承诺):错误:No Provider…) - Angular 2 No Provider or DI error (Uncaught (in promise): Error: No provider …) angular 4错误:未捕获(承诺):错误:没有ConnectionBackend的提供程序! 在注入Jsonp时 - angular 4 Error: Uncaught (in promise): Error: No provider for ConnectionBackend! while injecting Jsonp 使用Karma的Angular测试中的错误:未捕获(承诺):错误:没有SessionUtil的提供程序 - Error in Angular Test using Karma: Uncaught (in promise): Error: No provider for SessionUtil Angular2“t 没有提供者!” 和未捕获(承诺):错误:DI 错误 - Angular2 "No provider for t!" and Uncaught (in promise): Error: DI Error 未捕获(在承诺中):错误:没有String的提供者 - Uncaught (in promise): Error: No provider for String 未发现(承诺中):错误:没有凭据提供者? - Uncaught (in promise): Error: No provider for Credentials? 未捕获(承诺):错误:没有 GooglePlus 的提供者 - Uncaught (in promise): Error: No provider for GooglePlus '错误:未捕获(承诺):没有Jsonp的提供者'(HTML / Javascript / Typescript / Angular2) - 'Error: Uncaught (in promise): No provider for Jsonp' (HTML / Javascript / Typescript / Angular2) 错误错误:未捕获(承诺):错误:没有布尔值的提供者 - ERROR Error: Uncaught (in promise): Error: No provider for Boolean 错误错误:未捕获(承诺中):错误:ActivatedRoute没有提供程序 - ERROR Error: Uncaught (in promise): Error: No provider for ActivatedRoute
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM