The Digital Ninja
The Digital Ninja

Reputation: 1120

Service referencing service, constructor causes DI error

Trying to create a real world app to wrap my api and I'm just not sure how to debug this error.

Constructing the "private authService" in lists.service seems to be the the base cause of the error. Login component works fine.

EXCEPTION: Uncaught (in promise): Error: DI Error Error: DI Error at NoProviderError.ZoneAwareError (http://localhost:4200/polyfills.bundle.js:3270:33) at NoProviderError.BaseError [as constructor] (http://localhost:4200/vendor.bundle.js:29085:16) at NoProviderError.AbstractProviderError [as constructor] (http://localhost:4200/vendor.bundle.js:57951:16) at new NoProviderError (http://localhost:4200/vendor.bundle.js:58013:16) at ReflectiveInjector_._throwOrNull (http://localhost:4200/vendor.bundle.js:78274:19)........

List service to fetch lists.

import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, Response } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';

import { AuthService } from '../auth/auth.service';

@Injectable()
export class ListsService {

  constructor(private http: Http, private authService: AuthService) { }

  getLists(): Observable<boolean> {
    // add jwt token to headers
    let headers = new Headers({ 'Authorization': 'Bearer ' + this.authService.token });
    let options = new RequestOptions({ headers: headers });

    return this.http.post('http://localhost:8080/lists', options)
      .map((response: Response) => response.json());
  }

}

Auth Service to get token

import { Injectable } from '@angular/core';
import { Http, Headers, Response } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map'

@Injectable()
export class AuthService {
  public token: string;

  constructor(private http: Http) {
    let currentUser = JSON.parse(localStorage.getItem('currentUser'));
    this.token = currentUser && currentUser.token;
  }

  login(email: string, password: string): Observable<boolean> {
    return this.http.post('http://localhost:8080/login', { email: email, password: password })
      .map((response: Response) => {
        let token = response.json() && response.json().token;
        if (token) {
          // set token
          this.token = token;
          localStorage.setItem('currentUser', JSON.stringify({ email: email, token: token }));
          return token;
        } else {
          return false;
        }
      }
    );
  }


  logout(): void {
    this.token = null;
    localStorage.removeItem('currentUser');
  }

}

Upvotes: 0

Views: 496

Answers (1)

The Digital Ninja
The Digital Ninja

Reputation: 1120

Looks like if you want a service, such as auth, to be available to all the other services you need to include it as a provider in the app.module

Upvotes: 1

Related Questions