Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 - inject singleton Service into Directive

I have problem with injecting singleton service into a directive. I have service:

@Injectable()
export class AuthService{ ... }

I put it into bootstrapper.

bootstrap(AppComponent, [AuthService, ...]);

I made directive, that protects my component:

@Directive({
  selector: '[protected]'
})
export class ProtectedDirective {
   constructor(private authService:AuthService) { ... }
}

... and added to one of components

@Component({
  selector: 'dashboard',
  directives: [ProtectedDirective],
  template: '<div protected></div',
})
export class DashboardCmp { }

In console i see an error:

ORIGINAL EXCEPTION: No provider for AuthService!

If I add a provider to DashboardCmp, everything works fine, but it's not a singleton service. I set its properties in other component and I don't see them when I'm in directive.

like image 958
Foxer Avatar asked Jan 22 '26 19:01

Foxer


1 Answers

I resolved my problem. Everything was fine but

import {AuthService} from '../services/auth.service'; (in protected.directive.ts)

is not equal to

import {AuthService} from '../Services/auth.service'; ( in main.ts)

Yes, it's stupid, but it made the dependency injection impossible.

like image 98
Foxer Avatar answered Jan 24 '26 18:01

Foxer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!