I've got a very simply service:
import { Injectable } from '@angular/core';
import { MdSnackBar, MdSnackBarConfig } from '@angular/material';
@Injectable()
export class AlertsService {
alerts: string[];
constructor(private snackBar: MdSnackBar) {
this.alerts = [];
}
public add(alert: string, action?: string, config?: MdSnackBarConfig) {
this.alerts.push(alert);
// console.warn('AlertsService::alerts =', this.alerts, ';');
this.snackBar.open(alert, action, config);
}
}
…and a module for its dep (import: [
ed by 'app.module'):
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MdSnackBarModule } from '@angular/material';
@NgModule({
imports: [
CommonModule, MdSnackBarModule
],
exports: [
MdSnackBarModule
]
})
export class AlertsModule { }
The Service is listed in 'app.module':
@NgModule({
declarations: [
AppComponent
],
imports: [
CommonModule,
BrowserModule,
FormsModule,
HttpModule,
BrowserAnimationsModule,
SomeComp1Module,
AlertsModule
],
providers: [
AlertsService
],
bootstrap: [AppComponent]
})
export class AppModule {
}
It's used like so:
@Component({
selector: 'app-some-comp1',
templateUrl: './some-comp1.component.html'
})
export class SomeComp1Component {
constructor(private alertsService: AlertsService) {
this.alertsService.add('SomeComp1Component');
}
}
Bug
TypeError: this.alerts is undefined
Making alerts
static, then gives me: TypeError: this.snackBar is undefined
.
My test-case doesn't replicate the bug. Clearly AlertsService
isn't being constructed/inject here. How do I debug the injector?
Solved it in a few different ways:
Bind
Now the
alertsService
actually showed correct output to the rendered browser view.Instance functions
Still was getting
TypeError: this.alerts is undefined
sometimes (from the exact same contextComp0::func0::this.alertsService
) so decided to try this other TypeScript recommended solution:Other
This
this
bug was annoying me so much that I regenerated all the code and migrated my original base back in with a 'fine toothed comb'. So not sure if it's related, but I found an extraBrowserAnimationsModule
import and some missingrxjs/add
imports.