【问题标题】:Error: Uncaught (in promise): Error: No provider for Service - Angular 4.1.2错误:未捕获(承诺):错误:没有服务提供者 - Angular 4.1.2
【发布时间】:2017-11-11 16:56:54
【问题描述】:

我是 Angular 的新手,我遇到了一些我不明白的烦人问题。我想将我的服务注入@NgModule,这样我就可以在应用程序的任何地方使用它,而无需再次声明或导入它。然后当我运行我的项目时,刷新页面后一切都很好并得到这个异常:

错误:未捕获(承诺):错误:没有服务提供者

ma​​ke.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());
    }

}

我在 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 {
}

最后在我的组件中使用它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);
  }

}

当我像这样在我的组件中声明提供者时:

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

然后一切正常,但这不是我想要存档的。

【问题讨论】:

  • app-vehicle-form 在哪个模块中?是否有任何机会延迟加载?
  • @Maximus 它在 app.module.shared.ts 文件中,您希望我显示其中的代码吗?我不知道它是否延迟加载,我该如何检查它?
  • 你使用路由吗?

标签: angular dependency-injection asp.net-core


【解决方案1】:

@Maximus 是的,我正在使用路由。我不知道为什么 Angular CLI 生成了 3 个单独的文件而不是一个。

这三个文件是: app.module.server.ts、app.module.shared.ts、app.module.client.ts

我不得不将 app.module.client 重命名为 app.module.ts 以从 CLI 生成组件,因为出现 app.module 文件丢失的错误。

我认为 app.module.client 现在是旧的 app.module 文件,它导入了另外两个文件 app.module.server 和 app.module.shared。

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' }
        ])
    ]
};

【讨论】:

    【解决方案2】:

    我认为你正在向风车倾斜。我最好将您的常量导出为某个类中的静态字段:

    some.settings.ts

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

    然后在ma​​ke.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());
        }
    }
    

    【讨论】:

    • ReferenceError: 位置未定义
    • @Voque,尝试从预渲染中排除库
    【解决方案3】:

    我也看到了同样的问题。但是,当我将提供者声明(依赖注入)放入我的根组件 app.component.ts 中时,我再也看不到这个问题了。

    最好的,

    【讨论】:

      猜你喜欢
      • 2018-02-27
      • 2017-10-11
      • 1970-01-01
      • 1970-01-01
      • 2017-06-21
      • 2017-11-18
      • 1970-01-01
      • 2018-04-03
      • 2022-12-19
      相关资源
      最近更新 更多