2
votes

I am trying to change the behaviours of my nav-bar component in Angular2, based on whether a user is logged in or not (an exported param in my user Service). I have just set isLoggedIn to return true for this. Unfortunately, the link isn't displaying, as:

angular2.js:23730 EXCEPTION: No Directive annotation found on UserService

I use UserService as a regular service in other places in the app, can I make it so it can also be used as a directive, without interfering with any of its other functionality?

nav.component.ts:

import { Component } from 'angular2/core';
import { RouteConfig, ROUTER_DIRECTIVES } from 'angular2/router';

import { UserService } from '../user/services/user.service';

@Component({
  selector: 'nav-bar',
  template: `
  <div class="nav">
    <a [routerLink]="['LoginComponent']" *ngIf="UserService.isLoggedIn">Login</a>
  </div>
  `,
  styleUrls: ['client/dev/todo/styles/todo.css'],
  directives: [ROUTER_DIRECTIVES, UserService],
  providers: [  ]
})

export class NavComponent {}

user.service.ts

import { Injectable, Inject } from 'angular2/core';
import { Headers, Http } from 'angular2/http';

@Injectable()
export class UserService {
  private loggedIn = false;

  constructor(@Inject(Http) private _http: Http) {
    this.loggedIn = !!localStorage.getItem('auth_token');
  }

  isLoggedIn() {
    //return this.loggedIn;
    return true;
  }
}

UPDATE:

Also, if I move the service to providers rather than directives, then the component doesn't display at all, error:

EXCEPTION: TypeError: Cannot read property 'isLoggedIn' of undefined in [UserService.isLoggedIn in NavComponent@2:41]

So it would seem I can't reference that property?

1

1 Answers

1
votes

You're injecting your service in your directives property, therefore is expecting a @Component or a @Directive.

directives: [ROUTER_DIRECTIVES, UserService], // <<< Not good! Remove it from there!

You have to inject in in your providers property

providers : [UserService] /// Good!

Edit

So your question is more like Can I use a Service as a Directive?, the answer would be no. You would have to annotate your Service with @Component or @Directive and by that time it wouldn't be a simple service anymore.