dopatraman
dopatraman

Reputation: 13908

Getting error injecting service into guard

I'm making a guard like so:

// MyGuard.ts
import { Injectable, Component } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, RouterStateSnapshot } from '@angular/router';

import { MyService } from './services/MyService';

@Component({
  providers: [MyService]
})

@Injectable()
export class MyGuard implements CanActivate {
  constructor(public s : MyService) {}

  canActivate(next: ActivatedRouteSnapshot, prev: RouterStateSnapshot) {
    this.s.doSomething();
    return true;
  }
}

The service is here:

// MyService.ts
import { Injectable } from '@angular/core';
import * as _ from 'lodash';

@Injectable()
export class MyService {
  constructor() {
  }

  public doSomething() {
    return this;
  }
}

When I load the page I get this error:

Error: Uncaught (in promise): No provider for MyService! (MyGuard -> MyService)

If I remove the line in the constructor of MyGuard where I declare the service

...
export class MyGuard implements CanActivate {
  constructor() {} // <--- here
  ...

I am able to load the page without any errors. What am I doing wrong?

Upvotes: 0

Views: 1004

Answers (2)

rashfmnb
rashfmnb

Reputation: 10538

you dont need to declare the service just add it to constructor and then use the variable using this

constructor(private myService: MyService) {
}

func()
{
this.myService //like this
}

and also add it to bootstrap like this

bootstrap(AppComponent, [ 
  APP_ROUTER_PROVIDERS,
  MyService
]).catch(err => console.error(err));

Upvotes: 0

Thierry Templier
Thierry Templier

Reputation: 202176

You need to specify the service MyService as a provider when bootstrapping your application:

bootstrap(AppComponent, [
  (...)
  MyService, MyGuard
]);

Upvotes: 1

Related Questions