Reputation: 681
For the purpose of this question I have created a StackBlitz. I was learning about services and wanted to incorporate a service into my application.However, as soon as I declare a constructor including my service, my application starts displaying a blank page.
Here's my app.component.ts :
import { Component, OnInit, VERSION } from '@angular/core';
import { SharedInfoService } from './shared-info.service';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
name = 'Angular Dev';
private listOfComponents: any[];
customerType: boolean;
customerName: string;
constructor(private _service: SharedInfoService) {}
ngOnInit(): void {
this.customerName = 'Angular Customer';
}
}
and here's my shared-info.service.ts
:
import { Injectable } from '@angular/core';
@Injectable()
export class SharedInfoService {
constructor() {}
public name = 'Darth Vader';
}
I am not able to figure out why just adding this constructor creates a blank page. Ass soon as I comment the constructor out the page goes back to displaying what it should. Which obviously would halt my progress with my application.
Is there something that I am missing?
Upvotes: 0
Views: 988
Reputation: 32535
Because you didnt declare how your service should be created/provided. Either use
@Injectable({
providedIn:"root"
})
export class SharedInfoService {
constructor() {}
public name = 'Darth Vader';
}
or add provider to your modules
@NgModule({
imports: [BrowserModule, FormsModule],
declarations: [AppComponent, HelloComponent],
providers: [SharedInfoService],
bootstrap: [AppComponent],
})
export class AppModule {}
Both will work (even if used together)
Upvotes: 2