簡體   English   中英

錯誤:未捕獲(承諾):錯誤:沒有服務提供程序-Angular 4.1.2

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

我是Angular的新人,我遇到了我不理解的煩人的問題。 我想將我的服務注入@NgModule,以便我可以在應用程序中的任何位置使用它,而無需再次聲明或導入它。 然后,當我運行我的項目時,刷新頁面后一切都很好,並得到以下異常:

錯誤:未捕獲(承諾):錯誤:沒有服務提供者

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());
    }

}

該服務在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]
})
...

然后一切正常,但這不是我要存檔的內容。

@Maximus是的,我正在使用路由。 我不知道為什么有角度的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' }
        ])
    ]
};

我想你在風車上傾斜。 我最好在某些類中將常量導出為靜態字段:

some.settings.ts

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

然后在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());
    }
}

我也看到您遇到同樣的問題。 但是,當我將提供程序聲明(依賴注入)放在我的根組件app.component.ts中時,這個問題就再也看不到了。

最好,

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM