Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
245 views
in Technique[技术] by (71.8m points)

angular - Why am i getting "No provider for serviceName error"?

I'm trying to share a value between 2 components. I have a ProjectView component that renders a ProjectViewBudget component as a "child"(it is generated inside a dynamic tab component with ComponentFactoryResolver) by using a simple service. The child changes this value, the parent only subscribes to it. For now I only used it in the child, to see it working, but i get this error, why?

[ Service ]

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable()
export class BudgetYearSelectionService {
    private yearSource = new BehaviorSubject(undefined);
    selectedYear = this.yearSource.asObservable();

    selectYear(year: number): void {
        this.yearSource.next(year);
    }
}

[ Child ]

...
import { BudgetYearSelectionService, ProjectPrintService } from 'app/modules/project/service';
import { Subscription } from 'rxjs';
...

@Component({
    selector: 'ain-project-view-budget',
    templateUrl: './budget.component.html',
    styleUrls: ['./budget.component.scss'],
    encapsulation: ViewEncapsulation.None,
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class ProjectViewBudgetComponent implements OnInit, OnDestroy {

    years: Array<number>;
    year: number;
    ...

    private subscriptions: Array<Subscription> = [];

    constructor(
        private store: Store<any>,
        private ref: ChangeDetectorRef,
        private printService: ProjectPrintService,
        private budgetYearSelection: BudgetYearSelectionService
    ) { }

    ngOnInit(): void {
        ...
        this.subscriptions.push(this.budgetYearSelection.selectedYear.subscribe(year => this.year = year));
    }

    ngOnDestroy(): void {
        this.subscriptions.forEach(subscription => {
            subscription.unsubscribe();
        });
    }

    onYearChange(year?: number): void {
        this.budgetYearSelection.selectYear(year);
        this.component = year === undefined ? ProjectViewBudgetOverviewComponent : ProjectViewBudgetYearComponent;
    }
    ...
}

[ app.module.ts ]

import { registerLocaleData } from '@angular/common';
import { HttpClient, HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import localeNl from '@angular/common/locales/en-NL';
import localeNlExtra from '@angular/common/locales/extra/en-NL';
import { LOCALE_ID, NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { RouteReuseStrategy } from '@angular/router';
import { ServiceWorkerModule } from '@angular/service-worker';
import { EffectsModule } from '@ngrx/effects';
import { TranslateLoader, TranslateModule } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { PerfectScrollbarModule } from 'ngx-perfect-scrollbar';
import { environment } from '../environments/environment';
import { RoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { AppInterceptor } from './app.interceptor';
import { LayoutModule } from './layout';
import { MaterialModule } from './material';
import { AinModule } from './modules/ain.module';
import { NotificationModule } from './modules/notification/notification.module';
import { PermissionModule } from './modules/permission';
import { CustomRouteReuseStategy } from './modules/shared/custom-route-reuse.strategy';
import { OfflineComponent, PageNotFoundComponent } from './pages';
import { AppEffects } from './redux/app.effects';

export function createTranslateLoader(http: HttpClient): TranslateHttpLoader {
    return new TranslateHttpLoader(http, 'assets/i18n/', '.json');
}

registerLocaleData(localeNl, localeNlExtra);

@NgModule({
    imports: [
        BrowserModule,
        BrowserAnimationsModule,
        FormsModule,
        ReactiveFormsModule,
        MaterialModule,
        HttpClientModule,
        TranslateModule.forRoot({
            loader: {
                provide: TranslateLoader,
                useFactory: (createTranslateLoader),
                deps: [HttpClient]
            }
        }),
        EffectsModule.forFeature([AppEffects]),
        PerfectScrollbarModule,
        MaterialModule,
        AinModule,
        NotificationModule,
        PermissionModule.forFeature(),
        RoutingModule,
        LayoutModule,
        ServiceWorkerModule.register('ngsw-worker.js', { enabled: environment.production })
    ],
    declarations: [
        AppComponent,
        OfflineComponent,
        PageNotFoundComponent
    ],
    bootstrap: [AppComponent],
    providers: [
        { provide: HTTP_INTERCEPTORS, useClass: AppInterceptor, multi: true },
        { provide: LOCALE_ID, useValue: 'en-NL' },
        { provide: RouteReuseStrategy, useClass: CustomRouteReuseStategy }
    ]
})
export class AppModule {
}

[ Error ]

core.js:5873 ERROR NullInjectorError: R3InjectorError(AppModule)[BudgetYearSelectionService -> BudgetYearSelectionService -> BudgetYearSelectionService]: 
  NullInjectorError: No provider for BudgetYearSelectionService!

I am trying to follow the 4th example here https://fireship.io/lessons/sharing-data-between-angular-components-four-methods/

question from:https://stackoverflow.com/questions/65939021/why-am-i-getting-no-provider-for-servicename-error

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Did you add service to any module?

Otherwise you might want to add providedIn root to service:

@Injectable({
  providedIn: 'root',
})
export class BudgetYearSelectionService {

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...